Why can overusing Context sometimes hurt performance in a large React app?
Short answer
Every component that reads a piece of Context using useContext will re render whenever that Context's value changes, even if the component only cares about a small part of that value.
Advertisement
AModel answer
Every component that reads a piece of Context using useContext will re render whenever that Context's value changes, even if the component only cares about a small part of that value. Putting too much unrelated data into a single large Context can cause many components to re render more often than necessary.
// Splitting one large context into smaller, focused contexts
const UserContext = React.createContext(null);
const ThemeContext = React.createContext('light');
// Now a component that only needs the theme is not affected by user updatesReal-world example
A team notices their whole app slows down every time a single small setting changes, and fixes it by splitting one giant AppContext into several smaller, focused contexts so unrelated components stop re rendering unnecessarily.
Likely follow-ups
- How would you combine Context with useMemo to reduce unnecessary re renders?
- When is a dedicated state management library a better choice than Context for performance reasons?
Related topics