Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

How to optimize Context value updates to prevent unnecessary re-renders?

One common problem with Context is that every consumer re-renders when the value changes — even if a part of the value is unrelated to the component.

Here’s how you can optimize:


1. Memoize the Context Value

Use useMemo to create a stable reference for the context value so that it only changes when necessary.

const contextValue = useMemo(() => ({ user, login, logout }), [user]);

Without useMemo, a new object is created on every render, causing unwanted re-renders.


2. Split Contexts

Instead of putting all your app’s state into a single Context, split into multiple smaller Contexts.

Example: Separate ThemeContext, AuthContext, SettingsContext instead of one giant AppContext.

This way, changes in the auth state won't trigger unnecessary re-renders in components that only care about the theme.


3. Selector Hooks (Advanced)

There are libraries like use-context-selector that allow you to subscribe only to specific parts of the context, improving performance dramatically.

Example:

const theme = useContextSelector(ThemeContext, c => c.theme);

Pro Tip: Always be mindful of what data you put into Context — only global, relatively stable data should be shared.