Skip to main content

Lesson 5 of 11

useReducer - State Machines in React

useReducer is useState for complex state - it separates state update logic from component logic. If you find yourself with 3+ related state variables or complex update conditions, useReducer makes the logic testable, predictable, and colocated.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

useReducer - The Pattern

useReducer - The Pattern
import { useReducer } from 'react';

// Define state and action types first
interface FetchState<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

type FetchAction<T> =
  | { type: 'LOADING' }
  | { type: 'SUCCESS'; payload: T }
  | { type: 'ERROR'; payload: string }
  | { type: 'RESET' };

// The reducer - pure function, easily testable in isolation
function fetchReducer<T>(state: FetchState<T>, action: FetchAction<T>): FetchState<T> {
  switch (action.type) {
    case 'LOADING':
      return { data: null, loading: true, error: null };
    case 'SUCCESS':
      return { data: action.payload, loading: false, error: null };
    case 'ERROR':
      return { data: null, loading: false, error: action.payload };
    case 'RESET':
      return { data: null, loading: false, error: null };
    default:
      return state;
  }
}

// Using the reducer in a component
function UserProfile({ userId }: { userId: string }) {
  const [state, dispatch] = useReducer(fetchReducer<User>, {
    data: null, loading: false, error: null,
  });

  useEffect(() => {
    dispatch({ type: 'LOADING' });
    fetchUser(userId)
      .then(user => dispatch({ type: 'SUCCESS', payload: user }))
      .catch(err => dispatch({ type: 'ERROR', payload: err.message }));
  }, [userId]);

  if (state.loading) return <Spinner />;
  if (state.error) return <ErrorMessage message={state.error} />;
  if (!state.data) return null;
  return <Profile user={state.data} />;
}

When useReducer Beats useState

  • Multiple related state variables that change together - instead of 3 separate setLoading, setData, setError calls, dispatch one action that updates all three atomically
  • Complex state transition logic - when next state depends on previous state in non-trivial ways (e.g., state machines: idle โ†’ loading โ†’ success/error โ†’ idle)
  • Testing state logic - reducers are pure functions; you can unit-test them completely independently of React with no setup
  • State updates from many places - when many event handlers update the same state, colocating logic in a reducer makes it easier to understand all possible state changes
  • When to stick with useState - for simple independent values (isOpen, count, selectedId) useState is less code with no meaningful tradeoffs

Common Mistakes - useReducer

  • Mutating state inside the reducer - always return a new object; `return { ...state, loading: true }` not `state.loading = true; return state`
  • Over-complicating with useReducer - if your state has 1-2 independent fields and simple updates, useState is cleaner; don't reach for useReducer by default
  • Not using discriminated union action types - avoid `{ type: string; payload?: any }` which defeats TypeScript type narrowing; each action type should have a specific payload type

Tip

Tip

Practice useReducer State Machines in React in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for useReducer - State Machines in React

Practice Task

Note

Practice Task - (1) Write a working example of useReducer State Machines in React from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with useReducer State Machines in React is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • useReducer is useState for complex state - it separates state update logic from component logic.
  • Multiple related state variables that change together - instead of 3 separate setLoading, setData, setError calls, dispatch one action that updates all three atomically
  • Complex state transition logic - when next state depends on previous state in non-trivial ways (e.g., state machines: idle โ†’ loading โ†’ success/error โ†’ idle)
  • Testing state logic - reducers are pure functions; you can unit-test them completely independently of React with no setup

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/11 done