Fix the object passed as the value prop to the Context provider changes every render
When using React context, we often write code similar to the following:
const [state, dispatch] = useReducer(myReducer, defaultState);
const value = { state, dispatch };
return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
What is wrong with this code? It is syntactically correct and it works, but it is not perfect. The warning message I received shows this:
The 'value' object passed as the value prop to the Context provider changes every render. To fix this consider wrapping it in a useMemo hook.
Fortunately, the error message helps to solve the problem. The
value
object is passed to the MyContext.Provider
changes every time the component re-renders, which can cause unnecessary re-renders in child components that consume the context.Solution
The solution is also indicated in the error message. Wrapping the value
object in a useMemo
hook can help optimize performance by only re-computing the value object when its dependencies change.
const [state, dispatch] = useReducer(myReducer, defaultState);
const value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return <MyContext.Provider value={value}>{children}</MyContext.Provider>;