I'm so confused of the dependency of React Hooks. Here's the example:
const memorizeValue = useMemo(() => {
return {
count,
setCount,
}
}, [count, setCount])
In React documentary:
Note
The array of dependencies is not passed as arguments to the function. Conceptually, though, that’s what they represent: every value referenced inside the function should also appear in the dependencies array. In the future, a sufficiently advanced compiler could create this array automatically.
count
and setCount
both inside useMemo's callback, if i doesn't pass setCount
in the dependency array, the eslint won't warning me, but count
will, so what's the difference?
why don't need pass setCount
? setCount
is inside useMemo, isn't it?
here's the codesandbox link:
https://codesandbox.io/s/react-codesandbox-forked-xfupk?file=/src/Demo1/index.js:254-363
I think i maybe misunderstand the document. Somebody point it out, thanks.
Check the useState docs
Note
React guarantees that
setState
function identity is stable and won’t change on re-renders. This is why it’s safe to omit from theuseEffect
oruseCallback
dependency list.
Assuming setCount
is the updater function of a useState
hook then it's guaranteed to be a stable reference.