Closed as not planned
Description
Problem
I often find that when I'm using useState
together with useCallback
, that my callbacks depend on the current state:
const [state, setState] = useState(initialState);
const myCallback = useCallback(
() => {
// .. do something with current `state`, other than purely updating it:
fetch(`https://example.com/${state}`);
},
[state] // need a dependency on `state`
);
return <>
<MyComponent callback={myCallback}>
</>;
This gives unnecessary performance issues, because my callback is updated with each state update. Depending on the situation of the state
and the components that take myCallback
as a prop, it can get pretty bad.
Current workaround
I'm finding myself often doing this, to avoid such performance penalties:
const [state, setState] = useState(initialState);
const stateRef = useRef(state);
// effect's job is purely to update the `stateRef`
useEffect(
() => stateRef.current = state,
[state]
);
const myCallback = useCallback(
() => {
// use `stateRef` instead
fetch(`https://example.com/${stateRef.current}`);
},
[] // can now be empty
);
Possible improvement
What I would like to suggest, is that useState
provides a way to access the current value for callbacks. E.g.:
const [state, setState, stateRef] = useState(initialState);
// now I can use stateRef.current for my callbacks
Any thoughts?