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

State management patterns

7 min read ยท
In this lesson7

At Jupiter Station you're managing many systems simultaneously - navigation, fuel, crew, communications. Each system needs data and must share it with other modules. In React, state management is one of the most important architectural challenges. Choosing the right pattern determines whether your application will be easy to maintain and scalable, or become a chaotic maze of dependencies.

The problem: Prop drilling

Before you learned about Context API, the only way to pass data down the component tree was prop drilling - manually passing props through every level. It's like sending messages through a chain of crew members, where each one has to repeat the message onward, even though they don't need it themselves.

// Prop drilling - 4 levels of passing!
function SpaceStation({ missionData }) {
  return <Deck missionData={missionData} />;
}

function Deck({ missionData }) {
  // Deck doesn't use missionData - just passes it along
  return <Room missionData={missionData} />;
}

function Room({ missionData }) {
  // Room doesn't use it either - passes it along
  return <Terminal missionData={missionData} />;
}

function Terminal({ missionData }) {
  // Only here is the data actually needed!
  return <p>Mission: {missionData.name}</p>;
}

At 4 levels it's still manageable, but at 8-10 levels (which is normal in large applications) the code becomes unreadable, and every change in data structure requires modifying many intermediate components.

State colocation - keep state close to where it's used

Before reaching for global solutions, consider state colocation - the principle of keeping state as close as possible to the components that need it. Not every piece of data needs to be global. It's like on a spaceship: the cockpit temperature doesn't need to be known in the engine room.

// BAD: Global state for local data
function App() {
  const [searchQuery, setSearchQuery] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [formData, setFormData] = useState({});
  // ... 20 other states

  return (
    <GlobalContext.Provider value={/* everything */}>
      <Dashboard />
    </GlobalContext.Provider>
  );
}

// GOOD: State close to where it's used
function App() {
  // Only truly global data
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState('dark');

  return (
    <AppContext.Provider value={{ user, theme }}>
      <Dashboard />
    </AppContext.Provider>
  );
}

function SearchPanel() {
  // Local state - only this component needs it
  const [searchQuery, setSearchQuery] = useState('');
  return <input value={searchQuery} onChange={e => setSearchQuery(e.target.value)} />;
}

Rule of thumb: if state is used only by a single component or its direct children - keep it local. Move it up (lifting state up) or to context only when distant branches of the component tree need it.

Context API - the built-in solution

Context API solves prop drilling without additional libraries. You learned about it earlier in this module. Its main strengths and limitations:

Strengths:

  • Built into React - zero additional dependencies
  • Simple API: createContext, Provider, useContext
  • Excellent for data that changes rarely (theme, auth, locale)

Limitations:

  • Every value change re-renders ALL consumers
  • No built-in caching for API data
  • Requires combining with useReducer for complex state
  • Difficult performance optimization in large applications
// Context API - good choice for ship configuration
const ShipConfigContext = createContext();

function ShipConfigProvider({ children }) {
  const [config, setConfig] = useState({
    theme: 'dark-nebula',
    language: 'en',
    soundEnabled: true,
  });

  return (
    <ShipConfigContext.Provider value={{ config, setConfig }}>
      {children}
    </ShipConfigContext.Provider>
  );
}

Redux - command center for large fleets

Redux is a proven state management pattern, inspired by the Flux architecture. It works like the central command center of a fleet - a single store holds the entire application state, and changes happen exclusively through dispatching actions. We write modern Redux with Redux Toolkit - createSlice defines state and reducers, and configureStore builds the store:

// Redux Toolkit - the modern Redux standard
import { createSlice, configureStore } from '@reduxjs/toolkit';

// Slice = a piece of state + reducers + actions in one place
const missionSlice = createSlice({
  name: 'mission',
  initialState: {
    crew: [],
    fuel: 100,
    destination: null,
    status: 'docked',
  },
  reducers: {
    // Immer lets us "mutate" state - RTK turns it into a safe update
    addCrewMember: (state, action) => {
      state.crew.push(action.payload);
    },
    setDestination: (state, action) => {
      state.destination = action.payload;
    },
    burnFuel: (state, action) => {
      state.fuel = Math.max(0, state.fuel - action.payload);
    },
    launch: (state) => {
      state.status = 'in-flight';
    },
  },
});

// createSlice automatically generates action creators
export const { addCrewMember, setDestination, burnFuel, launch } = missionSlice.actions;

// configureStore builds the store (with DevTools and middleware included)
const store = configureStore({
  reducer: {
    mission: missionSlice.reducer,
  },
});

// Usage in a component:
function MissionControl() {
  const dispatch = useDispatch();
  const { crew, fuel, status } = useSelector(state => state.mission);

  return (
    <div>
      <p>Status: {status} | Fuel: {fuel}% | Crew: {crew.length}</p>
      <button onClick={() => dispatch(launch())}>Launch!</button>
      <button onClick={() => dispatch(burnFuel(10))}>Burn fuel</button>
    </div>
  );
}

When Redux?

  • Applications with many developers (clear rules, predictable data flow)
  • Complex state with many related actions
  • You need DevTools with time-travel debugging
  • Middleware for handling side-effects (thunks, sagas)

When NOT Redux?

  • Simple applications with few states
  • Small team or solo developer
  • Primarily API data (React Query is better)

Zustand - the lightweight maneuvering thruster

Zustand is a minimalist state management library. If Redux is the main engine, Zustand is the agile maneuvering thruster - it does the same thing, but with less overhead. No providers, no boilerplate, no Context API re-render problems.

// Zustand - simple store without providers
// import { create } from 'zustand';

// Creating a store - that's all you need!
// const useShipStore = create((set) => ({
//   fuel: 100,
//   position: { x: 0, y: 0 },
//   crew: 5,
//
//   burnFuel: (amount) => set((state) => ({
//     fuel: Math.max(0, state.fuel - amount)
//   })),
//
//   moveTo: (x, y) => set({ position: { x, y } }),
//
//   addCrew: () => set((state) => ({
//     crew: state.crew + 1
//   })),
// }));

// Usage in a component - no Provider needed!
function FuelGauge() {
  // Component re-renders ONLY when fuel changes
  // const fuel = useShipStore((state) => state.fuel);
  // return <div>Fuel: {fuel}%</div>;
}

function NavigationPanel() {
  // Reads ONLY position - a fuel change doesn't cause a re-render
  // const position = useShipStore((state) => state.position);
  // const moveTo = useShipStore((state) => state.moveTo);
  // return <button onClick={() => moveTo(10, 20)}>Fly!</button>;
}

Zustand automatically optimizes re-renders thanks to selectors. Each component subscribes only to the data it actually uses. A fuel change doesn't re-render the navigation panel - and vice versa.

Pattern comparison - galaxy map

FeatureContext APIRedux ToolkitZustand
Size0 KB (built-in)~11 KB~1.5 KB
BoilerplateMediumLarge (but RTK helps)Minimal
Re-rendersAll consumersOptimized (selectors)Optimized (selectors)
DevToolsNo dedicated onesExtensive (time-travel)Redux DevTools extension
Learning curveEasySteepEasy
Best forTheme, auth, localeLarge apps, large teamsMost applications

The tool selection principle

At Jupiter Station every system has its purpose. The same goes for state management:

  1. Local state (useState) - data needed only by a single component or its direct children
  2. Lifted state - data shared by 2-3 nearby components, move it to their common parent
  3. Context API - global data that changes rarely: theme, auth, locale, language
  4. Zustand - global state in small/medium applications when you need performance and simplicity
  5. Redux Toolkit - large applications with many developers, complex business logic, need for DevTools

Remember: there is no single best solution. The best space engineers match the tool to the problem, not the problem to the tool.

Test the pattern comparison in the editor below:

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

// === STATE MANAGEMENT PATTERNS ===

// Demo: Comparison of state management patterns
// 1. Context API - built into React
const ThemeContext = React.createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('dark-nebula');
  const toggleTheme = () => setTheme(t => t === 'dark-nebula' ? 'light-star' : 'dark-nebula');
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error('useTheme must be inside ThemeProvider');
  return ctx;
}

// 2. useReducer - Redux-like pattern built into React
const missionReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_CREW':
      return { ...state, crew: [...state.crew, action.payload] };
    case 'SET_DESTINATION':
      return { ...state, destination: action.payload };
    case 'BURN_FUEL':
      return { ...state, fuel: Math.max(0, state.fuel - action.payload) };
    case 'LAUNCH':
      return { ...state, status: 'in-flight' };
    case 'DOCK':
      return { ...state, status: 'docked', fuel: 100 };
    default:
      return state;
  }
};

const initialMission = {
  crew: ['Captain Ra', 'Navigator Nova'],
  fuel: 100,
  destination: null,
  status: 'docked',
};

// === DEMO PANELS ===

function ContextDemo() {
  const { theme, toggleTheme } = useTheme();
  const isDark = theme === 'dark-nebula';
  return (
    <div style={{ ...styles.panel, background: isDark ? '#1a2035' : '#e8eaf6' }}>
      <h3 style={{ color: '#4fc3f7' }}>Context API</h3>
      <p style={{ color: isDark ? '#ccc' : '#333', fontSize: 13 }}>
        Theme: <strong>{theme}</strong>
      </p>
      <p style={{ color: isDark ? '#888' : '#666', fontSize: 11 }}>
        Ideal for: theme, auth, locale
      </p>
      <button style={styles.btn} onClick={toggleTheme}>Change theme</button>
    </div>
  );
}

function ReducerDemo() {
  const [state, dispatch] = useReducer(missionReducer, initialMission);
  const destinations = ['Mars', 'Europa', 'Titan', 'Kepler-442b'];

  return (
    <div style={styles.panel}>
      <h3 style={{ color: '#ffd700' }}>useReducer (Redux-like)</h3>
      <div style={styles.stats}>
        <div>Status: <span style={{ color: state.status === 'in-flight' ? '#69f0ae' : '#ffd700' }}>{state.status}</span></div>
        <div>Fuel: <span style={{ color: state.fuel < 30 ? '#ff5252' : '#69f0ae' }}>{state.fuel}%</span></div>
        <div>Destination: <span style={{ color: '#4fc3f7' }}>{state.destination || 'none'}</span></div>
        <div>Crew: {state.crew.join(', ')}</div>
      </div>
      <div style={styles.btnRow}>
        {state.status === 'docked' ? (
          <>
            <button style={styles.btn} onClick={() => {
              const dest = destinations[Math.floor(Math.random() * destinations.length)];
              dispatch({ type: 'SET_DESTINATION', payload: dest });
            }}>Choose destination</button>
            {state.destination && (
              <button style={{ ...styles.btn, background: 'rgba(105,240,174,0.2)', borderColor: '#69f0ae' }}
                onClick={() => dispatch({ type: 'LAUNCH' })}>
                Start!
              </button>
            )}
          </>
        ) : (
          <>
            <button style={styles.btn} onClick={() => dispatch({ type: 'BURN_FUEL', payload: 15 })}>
              Engines (-15)
            </button>
            <button style={{ ...styles.btn, background: 'rgba(255,215,0,0.2)' }}
              onClick={() => dispatch({ type: 'DOCK' })}>
              Dock
            </button>
          </>
        )}
      </div>
    </div>
  );
}

function ColocationDemo() {
  // Local state - doesn't need Context or Redux
  const [localSearch, setLocalSearch] = useState('');
  const [results, setResults] = useState([]);

  const planets = ['Mars', 'Jupiter', 'Saturn', 'Neptune', 'Venus', 'Mercury', 'Uranus', 'Pluto'];

  const handleSearch = (query) => {
    setLocalSearch(query);
    if (query.length > 0) {
      setResults(planets.filter(p => p.toLowerCase().includes(query.toLowerCase())));
    } else {
      setResults([]);
    }
  };

  return (
    <div style={styles.panel}>
      <h3 style={{ color: '#ce93d8' }}>State Colocation</h3>
      <p style={{ color: '#888', fontSize: 11, marginBottom: 8 }}>
        Local state - without Context/Redux
      </p>
      <input
        style={styles.input}
        placeholder="Search for a planet..."
        value={localSearch}
        onChange={e => handleSearch(e.target.value)}
      />
      {results.length > 0 && (
        <div style={styles.resultList}>
          {results.map(r => (
            <div key={r} style={styles.resultItem}>{r}</div>
          ))}
        </div>
      )}
    </div>
  );
}

function ComparisonTable() {
  const data = [
    { pattern: 'useState', size: '0 KB', reRenders: 'Local', bestFor: 'Single component state' },
    { pattern: 'Context API', size: '0 KB', reRenders: 'All consumers', bestFor: 'Theme, auth, locale' },
    { pattern: 'useReducer', size: '0 KB', reRenders: 'Local', bestFor: 'Complex state logic' },
    { pattern: 'Redux (RTK)', size: '~11 KB', reRenders: 'Selective', bestFor: 'Large apps, teams' },
    { pattern: 'Zustand', size: '~1.5 KB', reRenders: 'Selective', bestFor: 'Most applications' },
  ];

  return (
    <div style={{ ...styles.panel, gridColumn: '1 / -1' }}>
      <h3 style={{ color: '#ffd700', textAlign: 'center' }}>Pattern comparison</h3>
      <div style={styles.table}>
        <div style={styles.tableHeader}>
          <span>Pattern</span><span>Size</span><span>Re-renders</span><span>Best for</span>
        </div>
        {data.map(row => (
          <div key={row.pattern} style={styles.tableRow}>
            <span style={{ color: '#4fc3f7' }}>{row.pattern}</span>
            <span>{row.size}</span>
            <span>{row.reRenders}</span>
            <span style={{ color: '#888' }}>{row.bestFor}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function App() {
  return (
    <ThemeProvider>
      <div style={styles.container}>
        <h1 style={styles.title}>State Management Patterns</h1>
        <p style={styles.subtitle}>
          Comparison of Context API, useReducer and state colocation
        </p>
        <div style={styles.grid}>
          <ContextDemo />
          <ReducerDemo />
          <ColocationDemo />
          <ComparisonTable />
        </div>
      </div>
    </ThemeProvider>
  );
}

const styles = {
  container: {
    fontFamily: 'Arial, sans-serif',
    background: 'linear-gradient(135deg, #0a0e1a 0%, #1a1a3e 100%)',
    minHeight: '100vh',
    padding: 24,
    color: 'white',
  },
  title: { textAlign: 'center', color: '#ffd700', marginBottom: 4 },
  subtitle: { textAlign: 'center', color: '#888', fontSize: 13, marginBottom: 24 },
  grid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
    gap: 16,
    maxWidth: 900,
    margin: '0 auto',
  },
  panel: {
    background: '#1a2035',
    borderRadius: 10,
    padding: 16,
    border: '1px solid rgba(79,195,247,0.2)',
  },
  stats: {
    fontSize: 13,
    lineHeight: 1.8,
    marginBottom: 12,
    padding: '8px 12px',
    background: 'rgba(0,0,0,0.3)',
    borderRadius: 8,
  },
  btnRow: { display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' },
  btn: {
    padding: '6px 16px',
    background: 'rgba(255,255,255,0.08)',
    color: 'white',
    border: '1px solid rgba(255,255,255,0.15)',
    borderRadius: 6,
    cursor: 'pointer',
    fontSize: 13,
  },
  input: {
    width: '100%',
    padding: '8px 12px',
    background: 'rgba(0,0,0,0.3)',
    color: 'white',
    border: '1px solid rgba(79,195,247,0.3)',
    borderRadius: 6,
    fontSize: 13,
    outline: 'none',
    boxSizing: 'border-box',
  },
  resultList: {
    marginTop: 8,
    background: 'rgba(0,0,0,0.2)',
    borderRadius: 6,
    overflow: 'hidden',
  },
  resultItem: {
    padding: '6px 12px',
    borderBottom: '1px solid rgba(255,255,255,0.05)',
    fontSize: 13,
    color: '#ce93d8',
  },
  table: { fontSize: 12 },
  tableHeader: {
    display: 'grid',
    gridTemplateColumns: '1fr 0.7fr 1fr 1.3fr',
    gap: 8,
    padding: '8px 0',
    borderBottom: '1px solid rgba(255,215,0,0.3)',
    fontWeight: 'bold',
    color: '#ffd700',
  },
  tableRow: {
    display: 'grid',
    gridTemplateColumns: '1fr 0.7fr 1fr 1.3fr',
    gap: 8,
    padding: '6px 0',
    borderBottom: '1px solid rgba(255,255,255,0.05)',
    color: '#ccc',
  },
};

export default App;

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. When should you use Context API instead of passing props (props drilling)?

  2. 2. What happens when one large context stores the ship position (updated 60x/s) and the fuel level, and a FuelGauge component reads only fuel?

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

Hands-on tasks in the game

  • Code editor

    Create three separate contexts (FuelContext, PositionContext, CrewContext) with their own providers. Compose them together in ShipProviders. Display data from each context in separate components.

  • Click in order

    Arrange the steps for creating a custom hook for safe context access:

  • Vertical ordering

    Arrange the stages of building a separated context system from outside to inside:

  • Code editor

    Implement a custom hook useFuelContext with context availability validation. Create a FuelProvider and a FuelPanel component that uses the hook.

  1. QuestionContext API vs Props Drilling
  2. QuestionRe-render Trap in Context API
  3. Coding taskPractice: Separated Contexts
  4. QuestionSplitting Contexts
  5. Click in orderCreating a Custom Hook for Context
  6. Put in orderProvider Composition
  7. Coding taskPractice: Custom Hook with Context Validation
  8. QuestionWhen NOT to Use Context API
  9. QuestionDebugging Complex State Flows

Useful articles