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

The init Function Parameter

Using useReducer's third parameter to pass a function that computes initial state lazily, running only on mount.

The init Function Parameter

What you'll learn: How to delay expensive initial state calculations in useReducer until the component actually mounts, improving performance.

The Problem Recap

In the previous lesson, you learned that passing a complex computation directly as useReducer's initial state runs that computation on every render, even though the result is only used once. This wastes resources.

The Solution: Lazy Initialization

useReducer accepts an optional third parameter: an init function. When provided, React calls this function with the second parameter as its argument, and uses the return value as the initial state.

const init = (initialArg) => {
  // Expensive computation runs ONLY on mount
  return computeExpensiveInitialState(initialArg);
};

const [state, dispatch] = useReducer(reducer, someValue, init);

The key difference: the init function runs only once when the component mounts, not on every re-render.

How It Works

  1. You pass three arguments to useReducer: (reducer, initialArg, init)
  2. On mount, React calls init(initialArg) to get the initial state
  3. On subsequent renders, React ignores the init function entirely

When to Use It

Use the third parameter when your initial state requires:

  • Parsing large data structures
  • Reading from localStorage
  • Complex calculations based on props
  • Any operation you want to run once, not repeatedly

Key Takeaway: The init function parameter in useReducer lets you compute initial state lazily—running expensive setup logic only on mount, avoiding unnecessary work on every re-render.