"How to read an often-changing value from useCallback?" doesn't seem idiomatic
Ninguém assumiu esta issue ainda.
- Linguagem predominante
- JavaScript
- Estrelas
- 11.8k
- Forks
- 7.9k
- Merge médio
- 1d 11h
- PRs com merge (30d)
- 11
Descrição
Custom hooks that take dependency arrays don't seem idiomatic (maybe I'm wrong). The biggest reason for that is that the React hooks lint doesn't check dependency arrays for anything except the primitive hooks.
In particular, I'd propose changing this:
function useEventCallback(fn, dependencies) {
const ref = useRef(() => {
throw new Error('Cannot call an event handler while rendering.');
});
useEffect(() => {
ref.current = fn;
}, [fn, ...dependencies]);
return useCallback(() => {
const fn = ref.current;
return fn();
}, [ref]);
}
to
function useEventCallback(fn) {
const ref = useRef(() => {
throw new Error('Cannot call an event handler while rendering.');
});
useEffect(() => {
ref.current = fn;
}, [fn]);
return useCallback(() => {
const fn = ref.current;
return fn();
}, []);
}
// which should be used as
const callback = useEventCallback(useCallback((event) => {
/* ... */
}, [/* dependencies */]));
This is slightly more abstract but also less likely to cause footguns. Alternatively, it might just be better to create a new function every render and store it in the ref (no use of dependencies at all).
function useEventCallback(fn) {
const ref = useRef(() => {
throw new Error('Cannot call an event handler while rendering.');
});
// Note this runs unconditionally
useEffect(() => {
ref.current = fn;
});
return useCallback(() => {
const fn = ref.current;
return fn();
}, []);
}
// which should be used as
const callback = useEventCallback((event) => {
/* ... */
});
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Direção de pesquisa
A issue menciona useEventCallback e useCallback e apresenta dois exemplos alternativos de arrays de dependências, mas não identifica arquivos do repositório nem testes. Comece localizando a documentação ou os exemplos que abrangem esses hooks; em seguida, determine qual recomendação deve ser adotada e atualize o material relevante com uma recomendação acordada.
Escrita pelo modelo de indexação a partir do texto da issue.
Avaliação
- Stack de tecnologia
- javascript, react
- Domínio
- documentation
- Tipo de issue
- Funcionalidade
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Status de atividade
- Estagnada
- Clareza
- Precisa de esclarecimento
- Facilidade para iniciantes
- 25/100