⚛️ React.js Intermediate

What is the Context API performance issue and how do you fix it?

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.