MediumState Management📖 Theory Question

What are the performance pitfalls of React Context and how do you avoid them?

💡

Hint

Every consumer re-renders when any value in context changes — split contexts by update frequency, memoize values, or use Zustand instead

Full Answer

The problem: All components that call useContext(MyContext) re-render whenever the context value changes — even if the specific part they use didn't change.

// ❌ One context for everything — user + theme + cart
// Any cart update re-renders Header (which only uses user.name)
const { user, cart, theme } = useContext(AppContext);

Fix 1: Split contexts by update frequency

// UserContext changes rarely, CartContext changes often
// Header subscribes to UserContext only — immune to cart updates
const { user } = useContext(UserContext);

Fix 2: Memoize the context value

const value = useMemo(() => ({ user, updateUser }), [user]);
// Without useMemo, a new object is created every render → all consumers re-render

Fix 3: Use a selector (context + useContextSelector)

// use-context-selector library — only re-renders when selected slice changes
const name = useContextSelector(UserContext, (ctx) => ctx.user.name);

Fix 4: Switch to Zustand/Jotai — atomic subscriptions by design; only components subscribed to a changed slice re-render.

More State Management Questions

EasyWhat is the difference between server state and client state?→EasyWhen would you choose Zustand over Redux Toolkit?→EasyWhat is React Query's staleTime vs gcTime (cacheTime) and how do they interact?→EasyWhat is optimistic updating and how do you implement it with React Query?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint