"How to read an often-changing value from useCallback?" doesn't seem idiomatic
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.8k
- Forks
- 7.9k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 11
Description
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) => {
/* ... */
});
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names useEventCallback and useCallback and presents two alternative dependency-array examples, but it does not identify repository files or tests. Start by locating the documentation or examples covering these hooks, then determine which guidance should be adopted and update the relevant material with an agreed recommendation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- documentation
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100