Course contentsShow
← React
Lesson 758 of 2,39620. useReducerFree lesson

Pure Function Requirements

Reducers must be pure: same inputs always produce same output, no side effects, no mutations.

Pure Function Requirements

You'll learn: Why reducers must be pure functions and what that means for your state updates.

What Makes a Reducer Pure?

A reducer must be a pure function. This means three critical rules:

  1. Same inputs → same output: Given identical state and action parameters, the reducer must always return the exact same new state
  2. No side effects: The reducer cannot make API calls, set timers, log to console, or interact with anything outside its scope
  3. No mutations: The reducer must not modify the existing state object—it must return a new object

Think of a reducer like a mathematical formula: f(2, 3) = 5 every single time. You can't get 5 sometimes and 6 other times. You can't change global variables while calculating. You can't modify the numbers you received as input.

Why These Rules Matter

React may call your reducer multiple times with the same inputs during rendering (especially in Strict Mode or Concurrent features). If your reducer isn't pure, you'll get unpredictable results.

Pure reducer:

function cartReducer(state, action) {
  // Returns NEW state, doesn't modify old state
  if (action.type === 'added') {
    return [...state, action.item]; // ✅ Creates new array
  }
  return state;
}

Impure reducer (broken):

function badReducer(state, action) {
  if (action.type === 'added') {
    state.push(action.item); // ❌ Mutates existing state!
    logToAnalytics(action);  // ❌ Side effect!
    return state;
  }
  return state;
}

Testing Purity

Call your reducer twice with identical inputs. If the outputs differ, or if something in your app changes beyond the returned state, it's not pure.

Key Takeaway: Reducers must be predictable, isolated functions: same inputs always yield the same output, with no mutations or side effects—this guarantees React can safely manage your state.