React Context API Performance Hit: Unrelated Consumers Re-rendering on Partial State Update

TechLab Editorial TeamPublished 74 views1 answer
0

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

The problem

A common way to share user data in a React 18 + TypeScript dashboard is a single UserContext whose value holds the user's userName, theme preference and permissions. As the dashboard grows, the React DevTools profiler starts showing components re-rendering when data they don't use changes. Switching the theme, for example, re-renders a header that only displays userName.

A minimal setup that shows the behaviour:

src/contexts/UserContext.tsx:

TypeScript
import React, { createContext, useState, useContext, ReactNode, useMemo, useCallback } from 'react';

interface UserInfo {
  userName: string;
  theme: 'light' | 'dark';
  permissions: string[];
}

interface UserContextType {
  userInfo: UserInfo;
  updateTheme: (newTheme: 'light' | 'dark') => void;
  updateUserName: (newName: string) => void;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [userInfo, setUserInfo] = useState<UserInfo>({
    userName: 'John Doe',
    theme: 'light',
    permissions: ['view_dashboard', 'edit_profile'],
  });

  const updateTheme = useCallback((newTheme: 'light' | 'dark') => {
    setUserInfo(prev => ({ ...prev, theme: newTheme }));
  }, []);

  const updateUserName = useCallback((newName: string) => {
    setUserInfo(prev => ({ ...prev, userName: newName }));
  }, []);

  // The context value object itself changes on any userInfo update
  const contextValue = useMemo(() => ({ userInfo, updateTheme, updateUserName }), [userInfo, updateTheme, updateUserName]);

  return (
    <UserContext.Provider value={contextValue}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};

src/components/ProfileHeader.tsx (consumes userName only):

TypeScript
import React from 'react';
import { useUser } from '../contexts/UserContext';

const ProfileHeader: React.FC = () => {
  const { userInfo } = useUser();
  console.log('ProfileHeader re-rendered, userName:', userInfo.userName);
  return (
    <header style={{ padding: '10px', borderBottom: '1px solid #ccc' }}>
      <h1>Welcome, {userInfo.userName}!</h1>
    </header>
  );
};

export default React.memo(ProfileHeader);

src/components/ThemeSwitcher.tsx (consumes theme and updates it):

TypeScript
import React from 'react';
import { useUser } from '../contexts/UserContext';

const ThemeSwitcher: React.FC = () => {
  const { userInfo, updateTheme } = useUser();
  console.log('ThemeSwitcher re-rendered, theme:', userInfo.theme);

  const toggleTheme = () => {
    updateTheme(userInfo.theme === 'light' ? 'dark' : 'light');
  };

  return (
    <button onClick={toggleTheme} style={{ margin: '10px' }}>
      Switch to {userInfo.theme === 'light' ? 'Dark' : 'Light'} Theme
    </button>
  );
};

export default React.memo(ThemeSwitcher);

src/App.tsx (main application component):

TypeScript
import React from 'react';
import { UserProvider } from './contexts/UserContext';
import ProfileHeader from './components/ProfileHeader';
import ThemeSwitcher from './components/ThemeSwitcher';
import SomeOtherComponent from './components/SomeOtherComponent'; // Imagine this is a large, complex component

const App: React.FC = () => {
  return (
    <UserProvider>
      <ProfileHeader />
      <ThemeSwitcher />
      <SomeOtherComponent /> {/* This component is often far down the tree */}
      <main style={{ padding: '20px' }}>
        <p>Dashboard content goes here...</p>
      </main>
    </UserProvider>
  );
};

export default App;

Expected behaviour: When the 'Switch Theme' button is clicked in ThemeSwitcher, only the ThemeSwitcher component and other components explicitly consuming userInfo.theme (or userInfo as a whole and reacting to theme changes) should re-render. ProfileHeader, which only uses userInfo.userName, should not re-render because userInfo.userName has not changed.

Actual behaviour: Both ThemeSwitcher and ProfileHeader re-render, along with every other component that calls useUser(). The console shows:

Code
ThemeSwitcher re-rendered, theme: light
ProfileHeader re-rendered, userName: John Doe
ThemeSwitcher re-rendered, theme: dark
ProfileHeader re-rendered, userName: John Doe

In a large dashboard where many expensive widgets read the context, this shows up as noticeable lag on slower devices.

Applies to React 18 and 19.

The question: how should the context (or the component structure) change so that components only re-render when the part of the state they use changes? Wrapping consumers in React.memo and memoizing the provider value with useMemo, as above, don't help.

Advertisement

1 Answer

0

This is expected behaviour for React Context, and React.memo on the consumers can't prevent it.

Why the Problem Occurs (Root Cause)

React Context does not perform a "deep" comparison of the value prop passed to the Provider. Instead, it relies on referential equality. Whenever the value prop's reference changes, all components that consume that context, regardless of which specific properties they access, are marked for re-render.

In the UserProvider above:

TypeScript
const [userInfo, setUserInfo] = useState<UserInfo>({
  userName: 'John Doe',
  theme: 'light',
  permissions: ['view_dashboard', 'edit_profile'],
});
// ...
const contextValue = useMemo(() => ({ userInfo, updateTheme, updateUserName }), [userInfo, updateTheme, updateUserName]);

When updateTheme is called, setUserInfo updates the userInfo state. Even though userName remains the same, setUserInfo creates a new object for userInfo ({ ...prev, theme: newTheme }). Because userInfo is a dependency in your useMemo for contextValue, the contextValue object itself also gets a new reference on every userInfo update. Since contextValue is the value prop of UserContext.Provider, its new reference re-renders every component that calls useContext(UserContext) (here, through useUser()), whichever fields it reads. React.memo only skips re-renders caused by a parent re-rendering with the same props. A component that reads a context is subscribed to it directly, and a context change re-renders it regardless of memo.

Components that don't read the context aren't affected. Because App passes ProfileHeader, ThemeSwitcher and SomeOtherComponent to the provider as children, those elements keep the same identity when the provider's state changes, so SomeOtherComponent only re-renders if it (or something inside it) calls useUser().

Corrected Code and Explanation

The most straightforward and idiomatic way to solve this with vanilla React Context is to split your context into more granular pieces. This way, consumers only subscribe to the specific pieces of state they need, reducing unnecessary re-renders.

Let's refactor your context into UserIdentityContext (for userName) and UserSettingsContext (for theme and permissions).

src/contexts/UserContexts.tsx (Note the plural 'Contexts' to indicate multiple):

TypeScript
import React, { createContext, useState, useContext, ReactNode, useCallback, useMemo } from 'react';

// --- User Identity Context (for userName) ---
interface UserIdentityContextType {
  userName: string;
  updateUserName: (newName: string) => void;
}

const UserIdentityContext = createContext<UserIdentityContextType | undefined>(undefined);

export const UserIdentityProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [userName, setUserName] = useState<string>('John Doe');

  const updateUserName = useCallback((newName: string) => {
    setUserName(newName);
  }, []);

  // Memoize the value to prevent unnecessary re-renders of consumers
  const value = useMemo(() => ({ userName, updateUserName }), [userName, updateUserName]);

  return (
    <UserIdentityContext.Provider value={value}>
      {children}
    </UserIdentityContext.Provider>
  );
};

export const useUserIdentity = () => {
  const context = useContext(UserIdentityContext);
  if (context === undefined) {
    throw new Error('useUserIdentity must be used within a UserIdentityProvider');
  }
  return context;
};

// --- User Settings Context (for theme and permissions) ---
interface UserSettingsContextType {
  theme: 'light' | 'dark';
  permissions: string[];
  updateTheme: (newTheme: 'light' | 'dark') => void;
}

const UserSettingsContext = createContext<UserSettingsContextType | undefined>(undefined);

export const UserSettingsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const [permissions, setPermissions] = useState<string[]>(['view_dashboard', 'edit_profile']);

  const updateTheme = useCallback((newTheme: 'light' | 'dark') => {
    setTheme(newTheme);
  }, []);

  // Memoize the value to prevent unnecessary re-renders of consumers
  const value = useMemo(() => ({ theme, permissions, updateTheme }), [theme, permissions, updateTheme]);

  return (
    <UserSettingsContext.Provider value={value}>
      {children}
    </UserSettingsContext.Provider>
  );
};

export const useUserSettings = () => {
  const context = useContext(UserSettingsContext);
  if (context === undefined) {
    throw new Error('useUserSettings must be used within a UserSettingsProvider');
  }
  return context;
};

src/components/ProfileHeader.tsx (now consumes UserIdentityContext):

TypeScript
import React from 'react';
import { useUserIdentity } from '../contexts/UserContexts'; // Changed import path and hook

const ProfileHeader: React.FC = () => {
  const { userName } = useUserIdentity(); // Only consumes userName
  console.log('ProfileHeader re-rendered, userName:', userName);
  return (
    <header style={{ padding: '10px', borderBottom: '1px solid #ccc' }}>
      <h1>Welcome, {userName}!</h1>
    </header>
  );
};

export default React.memo(ProfileHeader);

src/components/ThemeSwitcher.tsx (now consumes UserSettingsContext):

TypeScript
import React from 'react';
import { useUserSettings } from '../contexts/UserContexts'; // Changed import path and hook

const ThemeSwitcher: React.FC = () => {
  const { theme, updateTheme } = useUserSettings(); // Only consumes theme and updateTheme
  console.log('ThemeSwitcher re-rendered, theme:', theme);

  const toggleTheme = () => {
    updateTheme(theme === 'light' ? 'dark' : 'light');
  };

  return (
    <button onClick={toggleTheme} style={{ margin: '10px' }}>
      Switch to {theme === 'light' ? 'Dark' : 'Light'} Theme
    </button>
  );
};

export default React.memo(ThemeSwitcher);

src/App.tsx (main application component, now nests providers):

TypeScript
import React from 'react';
import { UserIdentityProvider, UserSettingsProvider } from './contexts/UserContexts'; // Import multiple providers
import ProfileHeader from './components/ProfileHeader';
import ThemeSwitcher from './components/ThemeSwitcher';
import SomeOtherComponent from './components/SomeOtherComponent';

const App: React.FC = () => {
  return (
    // Nest providers. Order generally doesn't matter unless one relies on the other.
    <UserIdentityProvider>
      <UserSettingsProvider>
        <ProfileHeader />
        <ThemeSwitcher />
        <SomeOtherComponent />
        <main style={{ padding: '20px' }}>
          <p>Dashboard content goes here...</p>
        </main>
      </UserSettingsProvider>
    </UserIdentityProvider>
  );
};

export default App;

When updateTheme runs, only UserSettingsProvider's value changes, so only components reading UserSettingsContext re-render. UserIdentityProvider's value keeps its reference, and ProfileHeader stays put.

A further refinement is to put the update functions in a context of their own. Components that only trigger updates, such as a button that changes the theme without displaying it, then never re-render when the value changes.

  1. Over-splitting Contexts: While splitting is good for performance, don't overdo it. If two pieces of state are almost always used together or frequently updated in tandem, splitting them might create more boilerplate without significant gains. Find the right logical separation for your application's concerns.
  2. useMemo Dependency Arrays: Ensure your useMemo hooks for context values have correct and stable dependency arrays. If you accidentally include a dependency that frequently changes its reference (e.g., an inline object or array without memoization), your context value will still change its reference, leading to the same re-render problem. This is why primitive values like userName and theme are ideal for useState and then directly used in useMemo for the context value.
  3. Alternative: The useContextSelector Pattern: For very large, monolithic context objects where splitting isn't practical or desired, libraries like use-context-selector (or state management libraries like Zustand which provide similar functionality) allow consumers to "select" only the parts of the context value they need. This hook then automatically handles memoization and ensures the component only re-renders if the selected value changes (using referential equality for the selected part). This can be a more elegant solution for complex, intertwined state that doesn't lend itself to simple splitting.

💡 Bonus Tip

For global state that changes often and is read in many places, an external store with selectors avoids the problem entirely. Zustand, for example, lets each component subscribe to a selected slice (useStore(s => s.userName)) and re-renders it only when that slice changes. Redux Toolkit's useSelector and Jotai's atoms work on the same principle. Before reaching for one, profile the slow interaction: a few unnecessary re-renders of cheap components rarely matter, and splitting the context is often enough.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.