In this article on state management with context API, the author applies useMemo to useState return values this way:
function CountProvider(props) {
const [count, setCount] = React.useState(0)
const value = React.useMemo(() => [count, setCount], [count])
return <CountContext.Provider value={value} {...props} />
}
I am not sure to understand the goal of this optimization:
- 1/ is it to prevent re-rendering in case any of the props change,
- 2/ or can setCount itself change spuriously?
If it is for 1/, isn't it equivalent to the following code? (because: what props other than children would we want to pass to the context provider? and if children change, a re-render is desirable)
function CountProvider({children}) {
const [count, setCount] = React.useState(0)
return (
<CountContext.Provider value={[count, setCount]}>
{children}
</CountContext.Provider>
);
}