JavaScript and React course Β· Module 4: Context API and useReducer

Optimizing Context API

5 min read Β·
In this lesson6

A mission command center handles hundreds of signals per second. If every signal caused a restart of all systems - the ship wouldn't make it to orbit. React works similarly: when a context value changes, every component consuming that context is re-rendered. In small applications this goes unnoticed, but in complex systems it can significantly slow things down.

The problem: excessive re-rendering with context

Consider a simple example. We have a single context storing the entire ship state:

const ShipContext = createContext();

function ShipProvider({ children }) {
  const [state, dispatch] = useReducer(shipReducer, {
    status: 'docked',
    fuel: 100,
    crewCount: 5,
    alerts: []
  });

  return (
    <ShipContext.Provider value={{ state, dispatch }}>
      {children}
    </ShipContext.Provider>
  );
}

function FuelGauge() {
  const { state } = useContext(ShipContext);
  console.log('FuelGauge is rendering');
  return <p>Fuel: {state.fuel}%</p>;
}

function AlertBell() {
  const { state } = useContext(ShipContext);
  console.log('AlertBell is rendering');
  return <p>Alerts: {state.alerts.length}</p>;
}

When alerts changes (e.g., a new alert), FuelGauge also re-renders - even though the fuel level hasn't changed. Any change to any field in state triggers rendering of all context consumers.

Solution 1: Split context into state and dispatch

The simplest and most effective optimization is splitting the context into two separate ones: one for state (which changes frequently), another for dispatch (which is stable throughout the component's lifetime):

const ShipStateContext = createContext();
const ShipDispatchContext = createContext();

function ShipProvider({ children }) {
  const [state, dispatch] = useReducer(shipReducer, initialState);

  return (
    <ShipDispatchContext.Provider value={dispatch}>
      <ShipStateContext.Provider value={state}>
        {children}
      </ShipStateContext.Provider>
    </ShipDispatchContext.Provider>
  );
}

// Dedicated hooks for each context
function useShipState() {
  return useContext(ShipStateContext);
}

function useShipDispatch() {
  return useContext(ShipDispatchContext);
}

Why does this work? The dispatch returned by useReducer is a stable reference - React guarantees that it doesn't change between renders. Components that only send actions (and don't display state) won't be re-rendered when state changes:

// This component re-renders only when state changes
function FuelGauge() {
  const state = useShipState();
  return <p>Fuel: {state.fuel}%</p>;
}

// This component does NOT re-render when ship state changes
// (because it only uses dispatch, and dispatch is stable)
function LaunchButton() {
  const dispatch = useShipDispatch();
  return (
    <button onClick={() => dispatch({ type: 'LAUNCH' })}>
      Launch
    </button>
  );
}

Solution 2: Split into multiple specialized contexts

Instead of one context for the entire state, we can create separate contexts for different functional areas. Components subscribe only to the context that concerns them:

// Separate context for fuel
const FuelContext = createContext();

function FuelProvider({ children }) {
  const [fuel, setFuel] = useState(100);
  const refuel = () => setFuel(100);
  const consumeFuel = (amount) => setFuel(prev => Math.max(0, prev - amount));

  return (
    <FuelContext.Provider value={{ fuel, refuel, consumeFuel }}>
      {children}
    </FuelContext.Provider>
  );
}

// Separate context for alerts
const AlertContext = createContext();

function AlertProvider({ children }) {
  const [alerts, setAlerts] = useState([]);
  const addAlert = (msg) => setAlerts(prev => [...prev, { id: Date.now(), msg }]);
  const dismissAlert = (id) => setAlerts(prev => prev.filter(a => a.id !== id));

  return (
    <AlertContext.Provider value={{ alerts, addAlert, dismissAlert }}>
      {children}
    </AlertContext.Provider>
  );
}

// FuelGauge re-renders only when fuel changes
function FuelGauge() {
  const { fuel } = useContext(FuelContext);
  return <p>Fuel: {fuel}%</p>;
}

// AlertBell re-renders only when alerts change
function AlertBell() {
  const { alerts } = useContext(AlertContext);
  return <p>Alerts: {alerts.length}</p>;
}

Solution 3: React.memo for child components

React.memo is a HOC (Higher-Order Component) that wraps a component and ensures it re-renders only when its props have changed. This is particularly useful for child components of providers:

// Without memo - re-renders every time the parent re-renders
function CrewMember({ name, role }) {
  console.log(`Rendering: ${name}`);
  return <li>{name} - {role}</li>;
}

// With memo - re-renders only when name or role change
const CrewMemberOptimized = React.memo(function CrewMember({ name, role }) {
  console.log(`Rendering: ${name}`);
  return <li>{name} - {role}</li>;
});

function CrewList() {
  const { state } = useShipState();
  return (
    <ul>
      {state.crew.map(member => (
        // CrewMemberOptimized doesn't re-render when fuel or status changes
        <CrewMemberOptimized
          key={member.id}
          name={member.name}
          role={member.role}
        />
      ))}
    </ul>
  );
}

When Context, when props?

Not all data should go into context. Here's a practical decision guide:

Use Context when:

  • Data is needed in many components at different levels of the tree
  • You're avoiding passing props through more than 2-3 levels (prop drilling)
  • Data changes rarely or concerns the broad application context (theme, language, user data)
// Good candidates for Context
const ThemeContext = createContext();        // theme (dark/light)
const AuthContext = createContext();         // logged-in user
const LanguageContext = createContext();     // interface language

Use props when:

  • Data flows through only 1-2 levels of components
  • The component is used multiple times in different contexts (reusable)
  • Data is specific to a particular UI section
// Better as props - this is component-specific data
function MissionCard({ mission, onSelect, isActive }) {
  return (
    <div className={isActive ? 'active' : ''} onClick={() => onSelect(mission)}>
      <h3>{mission.name}</h3>
      <p>{mission.status}</p>
    </div>
  );
}

Practical rule

Before adding something to context, ask yourself: "Do I really need this globally, or is it just prop drilling that I can solve with better component structure?"

// Sometimes the prop drilling problem can be solved through composition
// instead of Context:

// Instead of passing onSelectMission through 3 levels...
function MissionControl() {
  const [selected, setSelected] = useState(null);

  return (
    // Pass a ready component as children, instead of a function as a prop
    <MissionList
      renderItem={(mission) => (
        <MissionCard
          mission={mission}
          isActive={selected?.id === mission.id}
          onSelect={setSelected}
        />
      )}
    />
  );
}

Context optimization is a balance between convenience and performance. For most applications, a basic split into a state context and a dispatch context is sufficient. More advanced techniques are worth applying when you actually observe performance issues.

Code for this lesson: App.jsx
import React, { createContext, useContext, useReducer, memo } from 'react';

// --- Separate contexts for state and dispatch ---
// Optimization: components that only dispatch don't re-render on state change
const StateContext = createContext();
const DispatchContext = createContext();

const initialState = {
  ships: [
    { id: 1, name: 'Apollo VII', fuel: 80, active: true },
    { id: 2, name: 'Orion II', fuel: 45, active: false },
    { id: 3, name: 'Hermes', fuel: 100, active: true },
  ],
  selectedId: null,
};

function reducer(state, action) {
  switch (action.type) {
    case 'SELECT_SHIP':
      return { ...state, selectedId: action.id };
    case 'REFUEL':
      return {
        ...state,
        ships: state.ships.map(s =>
          s.id === action.id ? { ...s, fuel: Math.min(100, s.fuel + 20) } : s
        ),
      };
    case 'TOGGLE_ACTIVE':
      return {
        ...state,
        ships: state.ships.map(s =>
          s.id === action.id ? { ...s, active: !s.active } : s
        ),
      };
    default:
      return state;
  }
}

function FleetProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>
  );
}

// Context access hooks
function useFleetState() { return useContext(StateContext); }
function useFleetDispatch() { return useContext(DispatchContext); }

// --- Components optimized with React.memo ---

// This component re-renders ONLY when a specific ship changes
const ShipCard = memo(function ShipCard({ ship }) {
  const dispatch = useFleetDispatch();
  console.log(`[RENDER] ShipCard: ${ship.name}`);
  return (
    <div style={{ ...cardStyle, border: ship.active ? '1px solid #4fc3f7' : '1px solid #333' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ color: ship.active ? '#4fc3f7' : '#888', fontWeight: 'bold' }}>
          {ship.name}
        </span>
        <span style={{ fontSize: 12, color: ship.active ? '#4caf50' : '#f44336' }}>
          {ship.active ? '● ACTIVE' : 'β—‹ INACTIVE'}
        </span>
      </div>
      <div style={{ margin: '8px 0' }}>
        <div style={{ fontSize: 12, color: '#adb5bd', marginBottom: 4 }}>
          Fuel: {ship.fuel}%
        </div>
        <div style={{ background: '#0a0e1a', borderRadius: 4, height: 8 }}>
          <div style={{
            width: `${ship.fuel}%`, height: '100%', borderRadius: 4,
            background: ship.fuel > 50 ? '#4caf50' : ship.fuel > 25 ? '#ff9800' : '#f44336',
          }} />
        </div>
      </div>
      <div style={{ display: 'flex', gap: 6 }}>
        <button onClick={() => dispatch({ type: 'REFUEL', id: ship.id })} style={btnStyle}>
          Refuel +20%
        </button>
        <button onClick={() => dispatch({ type: 'TOGGLE_ACTIVE', id: ship.id })} style={btnStyle}>
          {ship.active ? 'Deactivate' : 'Activate'}
        </button>
      </div>
    </div>
  );
});

// This component re-renders on every state change (reads entire state)
const FleetStats = memo(function FleetStats() {
  const { ships } = useFleetState();
  console.log('[RENDER] FleetStats');
  const active = ships.filter(s => s.active).length;
  const avgFuel = Math.round(ships.reduce((sum, s) => sum + s.fuel, 0) / ships.length);
  return (
    <div style={{ ...cardStyle, display: 'flex', gap: 20, justifyContent: 'center' }}>
      <span style={{ color: '#adb5bd' }}>Active: <b style={{ color: '#4fc3f7' }}>{active}/{ships.length}</b></span>
      <span style={{ color: '#adb5bd' }}>Avg. fuel: <b style={{ color: '#ffd700' }}>{avgFuel}%</b></span>
    </div>
  );
});

// This component only dispatches - does NOT re-render on state change
const ResetButton = memo(function ResetButton() {
  const dispatch = useFleetDispatch();
  console.log('[RENDER] ResetButton - should render only once!');
  return (
    <button
      onClick={() => dispatch({ type: 'RESET' })}
      style={{ ...btnStyle, width: '100%', padding: '10px', marginTop: 8 }}
    >
      Reset fleet
    </button>
  );
});

function ShipList() {
  const { ships } = useFleetState();
  console.log('[RENDER] ShipList');
  return (
    <div>
      {ships.map(ship => (
        <ShipCard key={ship.id} ship={ship} />
      ))}
    </div>
  );
}

export default function App() {
  return (
    <FleetProvider>
      <div style={{ minHeight: '100vh', background: '#0a0e1a', padding: 24, fontFamily: 'Arial', color: 'white' }}>
        <h1 style={{ textAlign: 'center', color: '#ffd700', marginBottom: 8 }}>
          Context API Optimization
        </h1>
        <p style={{ textAlign: 'center', color: '#778da9', marginBottom: 20, fontSize: 13 }}>
          Open console (F12) to see which components re-render
        </p>
        <FleetStats />
        <ShipList />
        <ResetButton />
      </div>
    </FleetProvider>
  );
}

const cardStyle = {
  background: '#1a2035', borderRadius: 10, padding: 14,
  marginBottom: 12, border: '1px solid rgba(255,255,255,0.1)',
};
const btnStyle = {
  background: 'rgba(79,195,247,0.1)', color: '#4fc3f7',
  border: '1px solid rgba(79,195,247,0.3)', borderRadius: 6,
  padding: '5px 10px', cursor: 'pointer', fontSize: 12,
};

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How can React.memo help optimize components using Context API?

  2. 2. How do you prevent unnecessary re-renders in components using Context API?

These are 2 of 8 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a space university system

  • Code editor

    Implement a genetic laboratory

  • Code editor

    Build a galactic social network

  • Vertical ordering

    Arrange the Provider nesting in a typical React application - from outermost:

  • Code editor

    Build a Context API system with useReducer for fleet management: ThemeContext, FleetContext, dispatch actions, and custom hooks

  • Horizontal ordering

    Arrange a correct dispatch call with an action object:

  • Vertical ordering

    Arrange when to switch from props to Context API - from simplest case:

  • Click in order

    Arrange the code for a space Provider:

  • Vertical ordering

    Arrange the Providers in a space application hierarchy:

  • Vertical ordering

    Arrange the lifecycle events during space context initialization:

  • Click in order

    Arrange the custom hook for context:

  • Horizontal ordering

    Arrange the syntax for creating a context in React:

  • Click in order

    Arrange the space action creators:

  • Horizontal ordering

    Arrange the syntax for creating a new context with a default value:

  • Vertical ordering

    Arrange the steps for testing components with Context API:

  • Horizontal ordering

    Arrange the syntax for initializing useReducer with a reducer and initial state:

  • Vertical ordering

    Arrange the process of migrating old space systems to Context API:

  1. QuestionReact.memo
  2. Coding taskPractice: Re-render Optimization
  3. QuestionContext API Optimization
  4. Coding taskPractice: Context with TypeScript
  5. QuestionSplitting Contexts
  6. QuestionError Handling
  7. Coding taskPractice: Complex Reducers
  8. Put in orderProvider Nesting Order
  9. Coding taskPractice: Fleet Management System
  10. Put in orderDispatch Call with Action
  11. Put in orderWhen to Use Context Instead of Props
  12. Click in orderProvider Setup
  13. Put in orderContext Hierarchy in Application
  14. Put in orderLifecycle Hooks in Context API
  15. Click in orderCustom Hook Pattern
  16. QuestionCustom Hook for Context API
  17. Put in orderCreating a Context
  18. Click in orderAction Creators
  19. QuestionuseReducer vs useState
  20. Put in orderCreating a Context with createContext
  21. Put in orderTesting Context API
  22. Put in orderuseReducer Initialization
  23. QuestionMemoizing Provider Values
  24. QuestionAction Creator in useReducer
  25. Put in orderLegacy System Migration Strategies

Useful articles