UseCallback(), are function paramaters always added ot the dependency array in default? whereas variables used directly wihtin the function’s body should only be added if I am sure they would be updated?
const User = ({}) => {
const [state, setState] = useState(1);
const randomVariable = 1;
const handle = useCallback((state) => {
const User = setState(state + randomVariable)
}, [state]);
return ( )
})
- Should both "state" and "randomVariable" be added to its dependency array?
- will "state" always be ‘automatically added’ (by the compiler?) to the dependency array because it’s in the function’s arguments?
- Whereas "randomVariable" has to be manually added to the dependency array (by me) depending on whether I plan to have "randomVariable" update frequently?
2
Answers
Any variable (or similar) that your callback function closes over should be in the dependency array, since if they aren’t, an old version of the callback function closing over a previous variable (or similar) will be reused, causing bugs.
state
– In your example,state
isn’t something the function closes over. it’s a parameter to the function. (It has the same name as a variable the function would close over, but because you’ve declared it as a function parameter, that takes precedence — shadows — the outer declaration.) Since that parameter is something your callback receives when called, rather than closing over, it doesn’t belong in the dependency array.randomVariable
– Your callback does close overrandomVariable
, so it needs to be in the dependency array so you’re getting an up-to-date version of your callback when it changes, rather than continuing to use a stale version of your callback using a stale version of the variable.So:
If
state
weren’t a parameter to the callback and you wanted to use the one the function closes over, it would also need to be in the dependency list, but your function doesn’t seem at first glance to need to use thestate
state member.You may find my answer here handy, it goes into more general detail on
useCallback
.(source: react.dev docs)