is useMemo required to manage state via the context API in reactjs?

There is a very simple theory to why you should use useMemo to memoize the values passed to the Context Provider. When you pass the value to Context Provider, either as an object or an array like:

return <CountContext.Provider value={{state, setCount}} {...props} />

or

return <CountContext.Provider value={[state, setCount]} {...props} />

What essentially happens is that every time the CountProvider component re-renders a new reference to object or array is being passed as value to CountContext.Provider and hence even if the actual value may not have changed, the Context consumers are re-rendered since the reference check fails for the value.

Now you may or may not need a useMemo depending on what logic you have in your ContextProvider. For instance, in your case the CountContext is just using one state i.e count and passes it on to the child and if the CountContext is one of the top level element which is not re-rendered by anything other than the count change then in that case whether you use useMemo or not makes no difference since the reference of the returned value from useMemo is also updated on count change

However if you have certain parents to CountProvider which can cause CountProvider to re-render, useMemo to memoize context value comes in handy to avoid re-rendering of all the context consumers

Leave a Comment