You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
The text was updated successfully, but these errors were encountered:
But you probably want to take a look at reactjs/rfcs#220 instead which has the same goal as the issue you're describing here (useCallback invalidation) but with a different proposal.
Problem
I often find that when I'm using
useState
together withuseCallback
, that my callbacks depend on the current state: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 takemyCallback
as a prop, it can get pretty bad.Current workaround
I'm finding myself often doing this, to avoid such performance penalties:
Possible improvement
What I would like to suggest, is that
useState
provides a way to access the current value for callbacks. E.g.:Any thoughts?
The text was updated successfully, but these errors were encountered: