Implement Virtualization for Long Lists :👈 👉:How to Profile React Apps with DevTools

Why React Context Can Cause Performance Issues

Why React Context Can Cause Performance Issues

1. Introduction

React Context provides a way to share data across multiple components without passing props manually through every level of the component tree. For example, consider this component hierarchy:

App
 |
 |-- Header
 |    |
 |    |-- UserProfile
 |
 |-- Sidebar
 |    |
 |    |-- Navigation
 |
 |-- Dashboard
      |
      |-- EmployeeList

Suppose the application needs to share the logged-in user information with Header, UserProfile, and Dashboard. Without Context, we may need to pass user information through multiple components using props. This is called prop drilling. Context solves this problem by allowing components to consume shared data directly. However, Context can introduce performance issues when its value changes frequently.

2. How React Context Works

Context consists of three main parts:
  1. Create Context: Create a Context object using createContext().
  2. Provide Context: Use the Context Provider to make a value available to descendant components.
  3. Consume Context: Use useContext() to access the shared value.
Example:
import { createContext, useContext, useState } from "react";
const UserContext = createContext(null);
function App() {
    const [user, setUser] = useState({
        name: "John",
        role: "Admin"
    });
    return (
        <UserContext.Provider value={{ user, setUser }}>
            <Header />
            <Dashboard />
        </UserContext.Provider>
    );
}
function Header() {
    const { user } = useContext(UserContext);
    return <h2>Welcome {user.name}</h2>;
}
function Dashboard() {
    const { user } = useContext(UserContext);
    return <p>Role: {user.role}</p>;
}

Both Header and Dashboard can access the user information without receiving it through props.

3. Why Can React Context Cause Performance Issues?

The main reason is that when a Context value changes, React updates the components that consume that Context. Let's understand this with an example.
Example: A Context containing multiple values

const AppContext = createContext(null);
function App() {
    const [user, setUser] = useState({
        name: "John"
    });
    const [theme, setTheme] = useState("light");
    const [notifications, setNotifications] = useState(0);
    return (
        <AppContext.Provider
            value={{
                user,
                theme,
                notifications,
                setUser,
                setTheme,
                setNotifications
            }}
        >
            <Header />
            <UserProfile />
            <ThemeSettings />
            <NotificationPanel />
        </AppContext.Provider>
    );
}

Suppose the user receives a new notification.
The following state changes:

setNotifications(10);

The Context value is recreated because a new object is created during the App render. As a result, all components consuming AppContext are scheduled to re-render, even if they only need the user or theme information.
For example:

  • UserProfile needs only user information.
  • ThemeSettings needs only theme information.
  • NotificationPanel needs only notification information.

However, all three components consume the same Context.
This is one of the most common React Context performance problems.

4. Understanding the Context Re-render Problem

Consider the following component:
function UserProfile() {
    const { user } = useContext(AppContext);
    console.log("UserProfile rendered");
    return <h3>{user.name}</h3>;
}

Even though UserProfile only uses user, it subscribes to the entire AppContext value. When notifications change, the Context value changes. React therefore schedules UserProfile for re-rendering too.
Important: React Context does not automatically track which individual properties of an object a component reads. A component subscribing to a Context is updated when that Context's value changes according to Object.is comparison.

5. Problem 1: Creating a New Context Object on Every Render

Consider this implementation:
function App() {
    const [count, setCount] = useState(0);
    const [user, setUser] = useState({
        name: "John"
    });
    return (
        <AppContext.Provider
            value={{
                user,
                count
            }}
        >
            <UserProfile />
            <button onClick={() => setCount(count + 1)}>
                Increase Count
            </button>
        </AppContext.Provider>
    );
}
What happens?
  1. The user clicks Increase Count.
  2. App re-renders because count changes.
  3. A new object is created for the Context value.
  4. React detects that the Context value has changed.
  5. Components consuming AppContext are scheduled to re-render.

Even though user has not changed, UserProfile may render again.
Solution: Stabilize the Context value with useMemo

function App() {
    const [count, setCount] = useState(0);
    const [user, setUser] = useState({
        name: "John"
    });
    const contextValue = useMemo(() => ({
        user,
        count
    }), [user, count]);
    return (
        <AppContext.Provider value={contextValue}>
            <UserProfile />
            <button onClick={() => setCount(count + 1)}>
                Increase Count
            </button>
        </AppContext.Provider>
    );
}

Important clarification: This useMemo example stabilizes the Context object when its dependencies have not changed. However, because count is a dependency, changing count still changes the Context value and updates its consumers.
To prevent unrelated updates, separate the Context values as explained below.

6. Problem 2: Putting Unrelated State in One Context

A common mistake is creating one global Context for every application state.
For example:

const GlobalContext = createContext(null);
function App() {
    const [user, setUser] = useState(null);
    const [theme, setTheme] = useState("light");
    const [cart, setCart] = useState([]);
    const [notifications, setNotifications] = useState([]);
    const value = {
        user,
        theme,
        cart,
        notifications,
        setUser,
        setTheme,
        setCart,
        setNotifications
    };
    return (
        <GlobalContext.Provider value={value}>
            <Application />
        </GlobalContext.Provider>
    );
}
Problem:
  • Adding an item to the cart changes the global Context value.
  • Components that only need the theme may also re-render.
  • Updating notifications can also update components that only need user information.
  • As the application grows, unnecessary rendering can increase.
Solution: Split Contexts by responsibility Instead of one GlobalContext, create separate Contexts.
const UserContext = createContext(null);
const ThemeContext = createContext(null);
const CartContext = createContext(null);
const NotificationContext = createContext(null);
Then provide them separately:
function App() {
    const [user, setUser] = useState(null);
    const [theme, setTheme] = useState("light");
    const [cart, setCart] = useState([]);
    const [notifications, setNotifications] = useState([]);
    return (
        <UserContext.Provider value={user}>
            <ThemeContext.Provider value={theme}>
                <CartContext.Provider value={cart}>
                    <NotificationContext.Provider value={notifications}>
                        <Application />
                    </NotificationContext.Provider>
                </CartContext.Provider>
            </ThemeContext.Provider>
        </UserContext.Provider>
    );
}

Now a component consuming ThemeContext does not subscribe to CartContext or NotificationContext.
Benefits:

  • Unrelated Context updates do not directly update consumers of other Contexts.
  • Each Context has a clear responsibility.
  • It becomes easier to maintain application state.

7. Problem 3: Unnecessary Re-renders in Large Component Trees

Consider the following component hierarchy:
App
 |
 |-- UserContext.Provider
       |
       |-- Dashboard
             |
             |-- Header
             |    |
             |    |-- UserProfile
             |
             |-- Sidebar
             |
             |-- EmployeeList
                  |
                  |-- EmployeeRow
                  |-- EmployeeRow
                  |-- EmployeeRow

Suppose UserProfile consumes UserContext.
When the user information changes, UserProfile will re-render.
When the user Context changes, React schedules UserProfile for an update.
However, if a component higher in the tree also consumes that Context and passes values down through props, its descendants may render as part of the normal parent-child rendering process.
This can make a large component tree expensive to update.
Solution 1: Move Context consumption closer to where the data is needed.
Solution 2: Use React.memo for expensive child components that receive unchanged props.
Example:

const EmployeeList = React.memo(function EmployeeList({
    employees
}) {
    console.log("EmployeeList rendered");
    return (
        <>
            {employees.map(employee => (
                <EmployeeRow
                    key={employee.id}
                    employee={employee}
                />
            ))}
        </>
    );
});

React.memo can prevent EmployeeList from rendering when its props remain unchanged. However, React.memo does not prevent a component from updating when it directly consumes a Context whose value changes.

8. Optimization Technique 1: Split Contexts

This is often the simplest and most effective solution.

Before optimization:
const AppContext = createContext(null);
// User, Theme, Cart and Notifications
// are all stored in one Context.
After optimization:
const UserContext = createContext(null);
const ThemeContext = createContext(null);
const CartContext = createContext(null);
const NotificationContext = createContext(null);
Each component should subscribe only to the Context values it actually needs. Example:
function ThemeSettings() {
    const theme = useContext(ThemeContext);
    return <p>Current theme: {theme}</p>;
}
function NotificationPanel() {
    const notifications = useContext(NotificationContext);
    return (
        <p>Notifications: {notifications.length}</p>
    );
}

Updating notifications does not change ThemeContext.

9. Optimization Technique 2: Use useMemo for Context Values

When a Context Provider exposes an object, useMemo can prevent unnecessary changes to the value reference when its dependencies remain unchanged.
Without useMemo:

function UserProvider({ children }) {
    const [user, setUser] = useState(null);
    const value = {
        user,
        setUser
    };
    return (
        <UserContext.Provider value={value}>
            {children}
        </UserContext.Provider>
    );
}
With useMemo:
function UserProvider({ children }) {
    const [user, setUser] = useState(null);
    const value = useMemo(() => ({
        user,
        setUser
    }), [user]);
    return (
        <UserContext.Provider value={value}>
            {children}
        </UserContext.Provider>
    );
}

Why does this help?
When the user state changes, the Context value is recreated. However, when user remains unchanged, useMemo prevents creating a new object for the Context value.
React state setter functions such as setUser have stable identities. Therefore, the Context value only needs to be recreated when user changes.
Important: useMemo does not prevent updates when user changes. It only avoids creating a new Context value when its dependencies are unchanged.

10. Optimization Technique 3: Separate State and Dispatch Contexts

This is particularly useful when many components need to update shared state but do not need to read its current value. Consider a Context that contains both state and its update function:

const CartContext = createContext(null);
function CartProvider({ children }) {
    const [cart, setCart] = useState([]);
    return (
        <CartContext.Provider
            value={{ cart, setCart }}
        >
            {children}
        </CartContext.Provider>
    );
}

A component that only needs to add an item still subscribes to the entire Context value. We can separate state and dispatch into different Contexts.
Implementation:

const CartStateContext = createContext(null);
const CartDispatchContext = createContext(null);
function CartProvider({ children }) {
    const [cart, setCart] = useState([]);
    return (
        <CartStateContext.Provider value={cart}>
            <CartDispatchContext.Provider value={setCart}>
                {children}
            </CartDispatchContext.Provider>
        </CartStateContext.Provider>
    );
}
Component that reads cart state:
function CartSummary() {
    const cart = useContext(CartStateContext);
    return <p>Items: {cart.length}</p>;
}
Component that only updates cart:
function AddToCartButton({ product }) {
    const setCart = useContext(CartDispatchContext);
    function handleAdd() {
        setCart(previous => [
            ...previous,
            product
        ]);
    }
    return (
        <button onClick={handleAdd}>
            Add to Cart
        </button>
    );
}

Why is this useful? The setCart function has a stable identity. Therefore, components consuming only CartDispatchContext are not notified merely because the cart state changed. This does not mean those components can never re-render. Their parent, props, or local state can still cause updates.

11. Optimization Technique 4: Use React.memo Carefully

React.memo can help when a component receives props that remain unchanged. Example:
const UserDetails = React.memo(function UserDetails({
    user
}) {
    console.log("UserDetails rendered");
    return (
        <div>
            <h3>{user.name}</h3>
            <p>{user.role}</p>
        </div>
    );
});

If the parent re-renders but passes the same user object reference, React.memo can skip rendering UserDetails.
Important: If UserDetails directly consumes a Context and that Context changes, React.memo will not block the Context-driven update.

12. Optimization Technique 5: Use a Selector-Based Context Library

React's built-in useContext subscribes to the entire Context value. Sometimes an application needs more granular subscriptions.
For example:

  • Component A needs only the user name.
  • Component B needs only the user role.
  • Component C needs only the notification count.

A selector-based Context solution can allow components to subscribe to selected parts of a shared value. One option is the use-context-selector library.
Example:

import {
    createContext,
    useContextSelector
} from "use-context-selector";
const AppContext = createContext(null);
function UserName() {
    const name = useContextSelector(
        AppContext,
        value => value.user.name
    );
    return <h3>{name}</h3>;
}
function UserRole() {
    const role = useContextSelector(
        AppContext,
        value => value.user.role
    );
    return <p>{role}</p>;
}

The selector allows a component to subscribe to a particular part of the Context value. When choosing this approach, use the library's own Context creation and Provider APIs consistently. Do not mix it with ordinary React createContext and useContext.

13. When Should You Use Context and When Should You Avoid It?

Context is not inherently slow. It is a good solution for values that need to be shared across a component tree. However, frequently changing shared state may require a different approach.

Requirement Recommended approach
Application theme React Context
Logged-in user information React Context
Language preference React Context
Frequently changing shared state Consider a selector-based state solution
Complex application-wide state Context with reducers or a state management library
Server data and caching Consider TanStack Query or another data-fetching solution
State used by one component Local useState or useReducer

Examples of alternative state management libraries include Redux Toolkit, Zustand, and Jotai. These libraries provide different subscription and update models. Choose based on application complexity and requirements rather than assuming every Context problem requires another library.

14. How to Identify Context Performance Problems

Use React Developer Tools to identify unnecessary rendering.
Step 1: Install React Developer Tools. Install the React Developer Tools browser extension.
Step 2: Open the Profiler. Open browser developer tools and select the React Profiler tab.
Step 3: Record interactions. Perform actions such as:

  • Changing the theme.
  • Adding a cart item.
  • Updating notifications.
  • Changing user information.

Step 4: Inspect component renders. Check which components rendered and how much time they consumed.
Step 5: Optimize the relevant Context. Try splitting Contexts, stabilizing provider values, moving state closer to consumers, or using selector-based subscriptions.
Important: A component rendering again does not automatically mean there is a performance problem. Profile the application and identify expensive or unnecessary work before optimizing.

15. Best Practices

  • Do not put all application state into one Context.
  • Split unrelated state into separate Contexts.
  • Use useMemo when providing object values and stable references are useful.
  • Separate state and dispatch Contexts when many components only need to update state.
  • Keep frequently changing local state close to the components that need it.
  • Use React.memo for expensive components with stable props, not as a universal solution.
  • Avoid unnecessary object and function creation in Provider values.
  • Use a state management library when application state becomes complex or requires granular subscriptions.
  • Use React DevTools Profiler before making performance changes.

16. Interview Questions and Answers

Q1. Why can React Context cause performance issues?

When a Context value changes, React schedules components consuming that Context for re-rendering. If a single Context contains unrelated values, updates to one value can cause unnecessary updates in components that use other values.

Q2. Does React Context re-render every component inside its Provider?

No. A Context update directly schedules components that consume that Context. Non-consuming descendants may also render because of normal parent-child rendering, but a Context update does not automatically force every descendant to render.

Q3. How does useMemo help optimize React Context?

useMemo stabilizes the Context value reference when its dependencies have not changed. This prevents unnecessary Context updates caused by creating a new object on every Provider render.

Q4. Does React.memo prevent Context-driven re-renders?

No. React.memo can skip rendering based on unchanged props, but it does not block updates caused by a Context consumed directly by the component.

Q5. What is the benefit of splitting Contexts?

It separates unrelated state into independent subscriptions. Updating one Context does not directly notify consumers of another Context.

Q6. Why separate state and dispatch Contexts?

Components that only need to update state can subscribe to a stable setter function instead of the frequently changing state value. This prevents them from being notified solely because the state changes.

Q7. Is React Context a replacement for Redux?

Not necessarily. Context is primarily a mechanism for sharing values across a component tree. Redux Toolkit provides additional state management capabilities such as centralized update logic, selectors, middleware, and development tooling.

Q8. When should you avoid React Context?

Avoid using one large Context for frequently changing, unrelated application state when it causes excessive updates. Consider splitting Contexts, localizing state, or using a state management solution with granular subscriptions.

Q9. Does useContext support selecting individual properties?

No. The built-in useContext subscribes to the Context value as a whole. It does not automatically track which object properties a component reads.

Q10. How would you optimize Context in a large enterprise React application?

I would divide Contexts based on responsibility, keep frequently changing state close to its consumers, memoize Provider values where useful, separate state and dispatch subscriptions when appropriate, and profile the application. For more complex state, I would consider a selector-based state management solution.

17. Quick Summary

Problem Solution
One Context contains unrelated state. Split Contexts by responsibility.
Provider creates a new object on every render. Use useMemo when appropriate.
Components only need to update state. Separate state and dispatch Contexts.
Expensive child components render unnecessarily. Consider React.memo and stable props.
Components need granular subscriptions. Consider selector-based Context or a state management library.
Unnecessary renders are difficult to identify. Use React DevTools Profiler.

Final takeaway: React Context is not inherently a performance problem. The main issue is how shared state is structured and updated. Keep Contexts focused, avoid unnecessary value changes, and use profiling to identify where optimization is actually needed.

🔙
Implement Virtualization for Long Lists :👈 👉:How to Profile React Apps with DevTools

Comments and Discussion