"How to read an often-changing value from useCallback?" doesn't seem idiomatic
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- JavaScript
- Estrellas
- 11.8k
- Forks
- 7.9k
- Merge medio
- 1 d 11 h
- PR fusionados (30 d)
- 11
Descripción
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) => {
/* ... */
});
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
El issue menciona useEventCallback y useCallback y presenta dos ejemplos alternativos de arrays de dependencias, pero no identifica archivos del repositorio ni tests. Empieza por localizar la documentación o los ejemplos que cubren estos hooks; después, determina qué recomendación debería adoptarse y actualiza el material correspondiente con una recomendación acordada.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- javascript, react
- Área
- documentation
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 25/100