"How to read an often-changing value from useCallback?" doesn't seem idiomatic
Nessuno ha ancora preso questa issue.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
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) => {
/* ... */
});
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
La issue nomina useEventCallback e useCallback e presenta due esempi alternativi di array delle dipendenze, ma non identifica file del repository né test. Inizia individuando la documentazione o gli esempi che riguardano questi hook, quindi determina quale indicazione dovrebbe essere adottata e aggiorna il materiale pertinente con una raccomandazione concordata.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, react
- Ambito
- documentation
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Da chiarire
- Idoneità per principianti
- 25/100