What is the Context API performance issue and how do you fix it?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
The main performance issue with React Context is that every consumer re-renders when the context value changes, even if the specific piece of data the consumer uses did not change. If you put { user, theme, locale } in one context, changing the user causes the theme and locale consumers to re-render unnecessarily. Solutions: (1) Split contexts: create separate contexts for frequently and infrequently changing data — UserContext, ThemeContext, LocaleContext. Consumers only subscribe to what they need. (2) Memoize the context value: const value = useMemo(() => ({ user, logout }), [user]) — prevents a new object reference every render from triggering all consumers. (3) Context selectors (library solution): libraries like use-context-selector implement selector-based context subscriptions. (4) Colocate context consumption: place context consumers close to where they are needed — smaller subtrees to re-render. (5) Move state down: if only a small subtree needs the state, lift it no higher than necessary. For high-frequency updates (counters, animations), avoid context — use Zustand or Jotai instead.
Pro Tip
This topic has React.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.
Previous
What is memoization in React and how do you implement it?
Next
What are React Portals use cases?