JavaScript and React course ยท Module 4: Context API and useReducer

Context and useReducer in practice

5 min read ยท
In this lesson6

You've already learned Context API and useReducer separately. Now it's time to combine these two tools into one complete state management system - just as a space mission command center connects all communication systems into one unified control panel.

Why combine Context with useReducer?

useReducer alone centralizes state logic, but the state remains local to a single component. Context API alone makes data globally available, but managing complex updates through setState becomes messy. Combining both gives us the best of both worlds:

  • Context - makes state and dispatch available to every component in the tree without prop drilling
  • useReducer - organizes all update logic in a single, testable function

Space analogy: Context is the ship's communication network that reaches every cabin. useReducer is the central computer that processes all commands. Together they form Mission Control - every crew member can send a command and receive the current status, without having to run through corridors with notes.

Pattern: context with state and dispatch

The key pattern involves placing both state and dispatch in the context value:

import { createContext, useContext, useReducer } from 'react';

// Create context
const MissionContext = createContext();

// Reducer with state logic
function missionReducer(state, action) {
  switch (action.type) {
    case 'SET_STATUS':
      return { ...state, status: action.payload };
    case 'ADD_CREW':
      return { ...state, crew: [...state.crew, action.payload] };
    case 'UPDATE_FUEL':
      return { ...state, fuel: Math.max(0, Math.min(100, action.payload)) };
    default:
      return state;
  }
}

// Provider - combines Context with useReducer
function MissionProvider({ children }) {
  const initialState = {
    status: 'docked',
    crew: ['Captain Nova'],
    fuel: 100
  };

  const [state, dispatch] = useReducer(missionReducer, initialState);

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

Custom context access hook

Instead of calling useContext(MissionContext) in every component, we create a dedicated hook. This is a standard convention that:

  • Protects against using context outside the provider (throws a readable error)
  • Simplifies imports in components
  • Facilitates future refactoring
function useMission() {
  const context = useContext(MissionContext);
  if (!context) {
    throw new Error('useMission must be used within a MissionProvider');
  }
  return context;
}

Using dispatch from child components

Every component inside the provider can now directly send actions - without passing functions through props:

function StatusPanel() {
  const { state, dispatch } = useMission();

  return (
    <div className="status-panel">
      <h3>Mission status: {state.status}</h3>
      <button onClick={() => dispatch({ type: 'SET_STATUS', payload: 'launching' })}>
        Begin launch
      </button>
      <button onClick={() => dispatch({ type: 'SET_STATUS', payload: 'orbiting' })}>
        Enter orbit
      </button>
      <button onClick={() => dispatch({ type: 'SET_STATUS', payload: 'docked' })}>
        Dock
      </button>
    </div>
  );
}

function CrewPanel() {
  const { state, dispatch } = useMission();
  const [newMember, setNewMember] = React.useState('');

  const addMember = () => {
    if (newMember.trim()) {
      dispatch({ type: 'ADD_CREW', payload: newMember.trim() });
      setNewMember('');
    }
  };

  return (
    <div className="crew-panel">
      <h3>Crew ({state.crew.length}):</h3>
      <ul>
        {state.crew.map((member, i) => (
          <li key={i}>{member}</li>
        ))}
      </ul>
      <input
        value={newMember}
        onChange={(e) => setNewMember(e.target.value)}
        placeholder="New crew member name"
      />
      <button onClick={addMember}>Add to crew</button>
    </div>
  );
}

Multiple reducers pattern

As the application grows, one large reducer becomes hard to maintain. We can split the logic into smaller reducers by domain and combine them in a root reducer:

// Navigation reducer
function navigationReducer(navState, action) {
  switch (action.type) {
    case 'SET_DESTINATION':
      return { ...navState, destination: action.payload, status: 'en route' };
    case 'ARRIVE':
      return { ...navState, location: navState.destination, destination: null, status: 'arrived' };
    default:
      return navState;
  }
}

// Onboard systems reducer
function systemsReducer(systemsState, action) {
  switch (action.type) {
    case 'TOGGLE_SHIELDS':
      return { ...systemsState, shields: !systemsState.shields };
    case 'SET_ENGINE_POWER':
      return { ...systemsState, enginePower: action.payload };
    default:
      return systemsState;
  }
}

// Root reducer combining both
function rootReducer(state, action) {
  return {
    navigation: navigationReducer(state.navigation, action),
    systems: systemsReducer(state.systems, action)
  };
}

// Provider with root reducer
function SpaceshipProvider({ children }) {
  const initialState = {
    navigation: { location: 'Earth', destination: null, status: 'docked' },
    systems: { shields: false, enginePower: 0 }
  };

  const [state, dispatch] = useReducer(rootReducer, initialState);

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

The multiple reducers pattern allows for a clean separation of concerns. Each mini-reducer handles its own area of state, but all actions flow through a single dispatch. This way a TOGGLE_SHIELDS action can simultaneously affect systems and navigation, if needed.

Complete Mission Control application

Below you can see all the elements brought together - from context definition, through the provider, to components using useMission:

import { createContext, useContext, useReducer } from 'react';

const MissionContext = createContext();

function missionReducer(state, action) {
  switch (action.type) {
    case 'LAUNCH':
      return { ...state, status: 'flying', fuel: state.fuel - 20 };
    case 'DOCK':
      return { ...state, status: 'docked', speed: 0 };
    case 'ADD_LOG':
      return { ...state, log: [...state.log, action.payload] };
    default:
      return state;
  }
}

function MissionProvider({ children }) {
  const [state, dispatch] = useReducer(missionReducer, {
    status: 'docked',
    fuel: 100,
    speed: 0,
    log: []
  });

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

function useMission() {
  return useContext(MissionContext);
}

// Component A - control panel
function ControlPanel() {
  const { state, dispatch } = useMission();
  return (
    <div>
      <button
        onClick={() => {
          dispatch({ type: 'LAUNCH' });
          dispatch({ type: 'ADD_LOG', payload: 'Mission started!' });
        }}
        disabled={state.status === 'flying'}
      >
        Launch
      </button>
    </div>
  );
}

// Component B - state display (separate tree branch)
function MissionLog() {
  const { state } = useMission();
  return (
    <ul>
      {state.log.map((entry, i) => <li key={i}>{entry}</li>)}
    </ul>
  );
}

// Application
function App() {
  return (
    <MissionProvider>
      <ControlPanel />
      <MissionLog />
    </MissionProvider>
  );
}

Notice that ControlPanel and MissionLog can be at different depths in the component tree and don't need to know about each other - they are only connected by the shared MissionProvider.

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

// --- Mission reducer ---
const initialState = {
  missions: [
    { id: 1, name: 'Mars Exploration', priority: 'high', completed: false },
    { id: 2, name: 'Jupiter Probe', priority: 'medium', completed: false },
  ],
};

function missionReducer(state, action) {
  switch (action.type) {
    case 'ADD_MISSION':
      return {
        ...state,
        missions: [
          ...state.missions,
          { id: Date.now(), name: action.name, priority: action.priority, completed: false },
        ],
      };
    case 'COMPLETE_MISSION':
      return {
        ...state,
        missions: state.missions.map(m =>
          m.id === action.id ? { ...m, completed: true } : m
        ),
      };
    case 'SET_PRIORITY':
      return {
        ...state,
        missions: state.missions.map(m =>
          m.id === action.id ? { ...m, priority: action.priority } : m
        ),
      };
    default:
      return state;
  }
}

// --- Context ---
const MissionContext = createContext();

function MissionProvider({ children }) {
  const [state, dispatch] = useReducer(missionReducer, initialState);
  return (
    <MissionContext.Provider value={{ state, dispatch }}>
      {children}
    </MissionContext.Provider>
  );
}

function useMission() {
  return useContext(MissionContext);
}

// --- Components ---
const priorityColors = { high: '#f44336', medium: '#ff9800', low: '#4caf50' };

function MissionList() {
  const { state, dispatch } = useMission();
  return (
    <div style={panel}>
      <h2 style={{ color: '#4fc3f7', marginTop: 0 }}>Mission list</h2>
      {state.missions.map(m => (
        <div key={m.id} style={{ ...missionItem, opacity: m.completed ? 0.5 : 1 }}>
          <span style={{ flex: 1 }}>{m.name}</span>
          <span style={{ color: priorityColors[m.priority], marginRight: 8 }}>
            [{m.priority}]
          </span>
          {!m.completed && (
            <>
              <select
                value={m.priority}
                onChange={e => dispatch({ type: 'SET_PRIORITY', id: m.id, priority: e.target.value })}
                style={selectStyle}
              >
                <option value="high">High</option>
                <option value="medium">Medium</option>
                <option value="low">Low</option>
              </select>
              <button
                onClick={() => dispatch({ type: 'COMPLETE_MISSION', id: m.id })}
                style={btnStyle}
              >
                Complete
              </button>
            </>
          )}
          {m.completed && <span style={{ color: '#4caf50' }}>Completed</span>}
        </div>
      ))}
    </div>
  );
}

function AddMission() {
  const { dispatch } = useMission();
  const [name, setName] = React.useState('');
  const [priority, setPriority] = React.useState('medium');

  const handleAdd = () => {
    if (!name.trim()) return;
    dispatch({ type: 'ADD_MISSION', name, priority });
    setName('');
  };

  return (
    <div style={panel}>
      <h2 style={{ color: '#4fc3f7', marginTop: 0 }}>New mission</h2>
      <input
        value={name}
        onChange={e => setName(e.target.value)}
        placeholder="Mission name..."
        style={inputStyle}
      />
      <select value={priority} onChange={e => setPriority(e.target.value)} style={selectStyle}>
        <option value="high">High priority</option>
        <option value="medium">Medium priority</option>
        <option value="low">Low priority</option>
      </select>
      <button onClick={handleAdd} style={{ ...btnStyle, background: '#4fc3f7', color: '#0a0e1a' }}>
        Add mission
      </button>
    </div>
  );
}

function MissionStats() {
  const { state } = useMission();
  const total = state.missions.length;
  const done = state.missions.filter(m => m.completed).length;
  return (
    <div style={{ ...panel, display: 'flex', gap: 20 }}>
      <span style={{ color: '#adb5bd' }}>Total: <b style={{ color: 'white' }}>{total}</b></span>
      <span style={{ color: '#adb5bd' }}>Completed: <b style={{ color: '#4caf50' }}>{done}</b></span>
      <span style={{ color: '#adb5bd' }}>Active: <b style={{ color: '#4fc3f7' }}>{total - done}</b></span>
    </div>
  );
}

export default function App() {
  return (
    <MissionProvider>
      <div style={{ minHeight: '100vh', background: '#0a0e1a', padding: 24, fontFamily: 'Arial', color: 'white' }}>
        <h1 style={{ textAlign: 'center', color: '#ffd700', marginBottom: 24 }}>
          Mission Command Center
        </h1>
        <MissionStats />
        <AddMission />
        <MissionList />
      </div>
    </MissionProvider>
  );
}

// --- Style ---
const panel = {
  background: '#1a2035',
  borderRadius: 10,
  padding: 16,
  marginBottom: 16,
  border: '1px solid rgba(79,195,247,0.2)',
};
const missionItem = {
  display: 'flex', alignItems: 'center', gap: 8,
  padding: '8px 0', borderBottom: '1px solid rgba(255,255,255,0.07)',
};
const btnStyle = {
  background: 'rgba(255,255,255,0.1)', color: 'white',
  border: '1px solid rgba(255,255,255,0.2)', borderRadius: 6,
  padding: '4px 10px', cursor: 'pointer',
};
const selectStyle = {
  background: '#0a0e1a', color: 'white',
  border: '1px solid rgba(79,195,247,0.3)', borderRadius: 6, padding: '4px 6px',
};
const inputStyle = {
  background: '#0a0e1a', color: 'white',
  border: '1px solid rgba(79,195,247,0.3)', borderRadius: 6,
  padding: '6px 10px', width: '100%', marginBottom: 8, boxSizing: 'border-box',
};

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. Why must reducer functions be 'pure functions' and not mutate state?

  2. 2. How do you implement lazy initialization in useReducer?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the state complexity progression - from simple to requiring useReducer:

  • Horizontal ordering

    Arrange the case syntax elements in a reducer from left to right:

  • Code editor

    Implement an intergalactic portal

  • Click in order

    Arrange the structure of a space reducer:

  • Code editor

    Build a galactic shopping center

  1. QuestionImmutability in Reducers
  2. Put in orderFrom useState to useReducer - Complexity Progression
  3. Put in orderSwitch Structure in Reducer
  4. Coding taskPractice: useContext Hook
  5. Click in orderReducer Structure
  6. Coding taskPractice: Context Composition
  7. QuestionLazy Initialization

Useful articles