Why do all components using a context re-render when its value changes, and how do you limit that?
React compares the Provider's value with Object.is. Passing a new object literal each render makes every consumer re-render. Memoise the value, split contexts by concern, or keep state close to where it is used.
Explain it simply
A context value is like a group message on the class WhatsApp group. Every member sees it, even those who only cared about the exam date and not the canteen menu. If the provider creates a brand-new object on every render, React thinks a new message arrived and notifies everybody.
value={{ user, logout }} creates a fresh object each time the provider's parent renders, so all consumers re-render even when user did not change.
Ways to reduce this: wrap the value in useMemo; split one big context into several small ones (for example data and actions separately); move the provider down so fewer components sit under it; or use a store library that supports selecting only a slice of state.
Example
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const value = useMemo(
() => ({ user, logout: () => setUser(null) }),
[user]
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}What to say in the interview
"Every consumer re-renders when the provider value changes by reference. I memoise the value with useMemo, split contexts so unrelated updates do not collide, and avoid putting fast-changing data like mouse position in context. If I need selective subscriptions, I use a store with selectors."
Common mistakes
- Putting rapidly changing values such as input text into a global context.
- Creating the value object inline without memoising.