Nov 7, 2026| 5 min| 4 Views|Engineering

Mastering React Context API: Preventing Re-render Storms and Performance Pitfalls.

Learn how to use React Context API effectively without tanking performance. Avoid re-render storms with state splitting, memoization, and custom consumption hooks.

MT

Muhammad Taha Siddiqui

Author

Mastering React Context API: Preventing Re-render Storms and Performance Pitfalls

React Context API Explained: Sharing State Across Components Without Prop Drilling

When multiple components need the same data, passing it through props can become difficult to maintain.

Imagine a React application with a Dashboard, Sidebar, and ThemePanel. The application stores the current theme, and the ThemePanel needs to display and update it.

Without Context API, the theme and its update function must be passed through every intermediate component, even when those components don't use them.

This is known as prop drilling. React Context provides a way to share values with components throughout a particular part of the component tree without manually forwarding props at every level.

Understanding Prop Drilling

Consider this example:

import { useState } from "react";

type Theme = "light" | "dark";

function App() {
  const [theme, setTheme] = useState<Theme>("light");

  const toggleTheme = () => {
    setTheme((current) =>
      current === "light" ? "dark" : "light"
    );
  };

  return (
    <Dashboard
      theme={theme}
      onToggleTheme={toggleTheme}
    />
  );
}

function Dashboard({
  theme,
  onToggleTheme,
}: {
  theme: Theme;
  onToggleTheme: () => void;
}) {
  return (
    <Sidebar
      theme={theme}
      onToggleTheme={onToggleTheme}
    />
  );
}

function Sidebar({
  theme,
  onToggleTheme,
}: {
  theme: Theme;
  onToggleTheme: () => void;
}) {
  return (
    <ThemePanel
      theme={theme}
      onToggleTheme={onToggleTheme}
    />
  );
}

function ThemePanel({
  theme,
  onToggleTheme,
}: {
  theme: Theme;
  onToggleTheme: () => void;
}) {
  return (
    <div>
      <h2>Current theme: {theme}</h2>

      <button onClick={onToggleTheme}>
        Toggle Theme
      </button>
    </div>
  );
}

export default App;

The state belongs to App, but ThemePanel is the component that actually needs it. Both Dashboard and Sidebar simply forward the theme and callback.

As more components are added between the parent and the component that needs the data, this approach can create unnecessary prop dependencies.

Context API lets us remove those intermediate props.

Creating a Context

React provides createContext() to create a Context object.

Create a ThemeContext.ts file:

import { createContext } from "react";

export type Theme = "light" | "dark";

interface ThemeContextType {
  theme: Theme;
  toggleTheme: () => void;
}

const ThemeContext = createContext<
  ThemeContextType | undefined
>(undefined);

export default ThemeContext;

The Context defines the values that will be shared:

  • ▸theme represents the current application theme.
  • ▸toggleTheme changes the theme.

The default value is undefined because the Context is expected to receive its actual value from a Provider. This also allows us to detect when a component is used outside the Provider.

Creating the Context Provider

The Provider is responsible for supplying the Context value to its descendant components.

Create ThemeProvider.tsx:

import { useState } from "react";
import type { ReactNode } from "react";

import ThemeContext, { type Theme } from "./ThemeContext";

interface ThemeProviderProps {
  children: ReactNode;
}

export function ThemeProvider({
  children,
}: ThemeProviderProps) {
  const [theme, setTheme] = useState<Theme>("light");

  const toggleTheme = () => {
    setTheme((currentTheme) =>
      currentTheme === "light" ? "dark" : "light"
    );
  };

  return (
    <ThemeContext.Provider
      value={{ theme, toggleTheme }}
    >
      {children}
    </ThemeContext.Provider>
  );
}

The useState Hook owns the theme state. Whenever toggleTheme is called, React updates that state and the Provider supplies the new value to its consumers.

The Provider's value prop is what makes the state and update function available to descendant components.

Accessing Context with useContext

Components can access the nearest matching Provider using React's useContext() Hook.

Instead of writing the same Context check in every component, create a reusable custom Hook.

Create useTheme.ts:

import { useContext } from "react";
import ThemeContext from "./ThemeContext";

export function useTheme() {
  const context = useContext(ThemeContext);

  if (context === undefined) {
    throw new Error(
      "useTheme must be used within ThemeProvider"
    );
  }

  return context;
}

This Hook returns the current theme and its update function. It also throws an error when used outside ThemeProvider, making incorrect Provider usage easier to identify during development.

Using Context Inside Components

Now update ThemePanel:

import { useTheme } from "../contexts/theme/useTheme";

export default function ThemePanel() {
  const { theme, toggleTheme } = useTheme();

  return (
    <div>
      <h2>Current theme: {theme}</h2>

      <button onClick={toggleTheme}>
        Toggle Theme
      </button>
    </div>
  );
}

Notice that ThemePanel no longer receives theme or onToggleTheme through props.

The component gets both directly from Context. The same approach can be used by other components that need access to the theme.

For example, a separate component can display the current theme:

import { useTheme } from "../contexts/theme/useTheme";

export default function ThemeStatus() {
  const { theme } = useTheme();

  return <p>Selected theme: {theme}</p>;
}

Both components consume the same Context value. Changing the theme in ThemePanel also updates ThemeStatus.

Wrapping Components with ThemeProvider

The Provider must be placed above every component that needs access to its Context.

Update App.tsx:

import { ThemeProvider } from "./contexts/theme/ThemeProvider";
import ThemePanel from "./components/ThemePanel";
import ThemeStatus from "./components/ThemeStatus";

function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      <ThemePanel />
      <ThemeStatus />
    </div>
  );
}

function App() {
  return (
    <ThemeProvider>
      <Dashboard />
    </ThemeProvider>
  );
}

export default App;

The component tree now looks like this:

App
└── ThemeProvider
    └── Dashboard
        ├── ThemePanel
        └── ThemeStatus

Both ThemePanel and ThemeStatus can access the same theme without receiving it through their parent components.

Organizing Context in a React Application

For a small application, a few Context files may be enough. As the application grows, separating each Context into its own folder keeps related code together.

One possible structure is:

src/
├── contexts/
│   ├── theme/
│   │   ├── ThemeContext.ts
│   │   ├── ThemeProvider.tsx
│   │   └── useTheme.ts
│   │
│   └── auth/
│       ├── AuthContext.ts
│       ├── AuthProvider.tsx
│       └── useAuth.ts
│
├── components/
│   ├── ThemePanel.tsx
│   └── ThemeStatus.tsx
│
├── App.tsx
└── main.tsx

When multiple Context Providers are needed, they can also be combined into a single application-level component:

import type { ReactNode } from "react";

import { ThemeProvider } from "./contexts/theme/ThemeProvider";
import { AuthProvider } from "./contexts/auth/AuthProvider";

interface AppProvidersProps {
  children: ReactNode;
}

export function AppProviders({
  children,
}: AppProvidersProps) {
  return (
    <AuthProvider>
      <ThemeProvider>
        {children}
      </ThemeProvider>
    </AuthProvider>
  );
}

The application can then be wrapped once with AppProviders, rather than nesting every Provider directly inside App.

When Should You Use Context API?

Context works well when multiple components need access to the same value across different levels of the component tree.

Common examples include:

  • ▸Authentication: Sharing the current user and authentication-related actions.
  • ▸Theme preferences: Providing light and dark theme settings.
  • ▸Language preferences: Making the selected language available throughout the application.
  • ▸Application configuration: Sharing settings required by different parts of the UI.

Context isn't necessary for every piece of state. When only a parent and

Thought it was useful?

Share this record with your engineering circle.

Keep Reading