I am trying to understand this (mostly very helpful) article which describe how to use react's context API to manage application-level state. For a simple application (in this case a basic counter application), it uses the following solution:
const CountContext = React.createContext()
function CountProvider(props) {
const [count, setCount] = React.useState(0)
const value = React.useMemo(() => [count, setCount], [count])
return <CountContext.Provider value={value} {...props} />
}
to provide the context, and then the following hook which can be used in a component somewhere down the component tree:
function useCount() {
const context = React.useContext(CountContext)
if (!context) {
throw new Error(`useCount must be used within a CountProvider`)
}
return context
}
My Question:
I'm struggling to understand why the useMemo
hook is needed here. There is no especially heavy computation involved here so I'm not sure why we're memoizing these values. Wouldn't this work just as well if the context provider looked as follows:
function CountProvider(props) {
const [count, setCount] = React.useState(0)
return <CountContext.Provider value={value} {...props} />
}
I feel like there is probably something that I'm missing!!
setCount
from your dependency array as React guarantees this function will never update. – Statesman