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

init Function Signature and Arguments

How the init function receives the initialArg (second parameter) and returns the initial state object.

init Function Signature and Arguments

You'll learn: How the init function receives useReducer's second parameter and transforms it into your initial state.

When you pass a third argument to useReducer, that function (the init function) doesn't just run blindly—it receives the second parameter you passed to useReducer as its only argument.

How the Flow Works

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

Here's what happens:

  1. React calls init(initialArg)
  2. Whatever init returns becomes your initial state
  3. The initialArg can be anything: a number, string, object, array

The Function Signature

function init(initialArg) {
  // Transform initialArg into initial state
  return computedInitialState;
}

The init function:

  • Receives: The initialArg (second parameter to useReducer)
  • Returns: The initial state object

Practical Example

function createInitialState(userId) {
  return {
    userId: userId,
    profile: expensiveProfileLookup(userId),
    settings: loadDefaultSettings(userId)
  };
}

// userId is passed to createInitialState
const [state, dispatch] = useReducer(
  reducer,
  currentUserId,  // This becomes the argument
  createInitialState  // This function receives currentUserId
);

Think of it like a chef receiving an ingredient order (initialArg) and preparing the final dish (initial state) before service begins.

Key Takeaway: The init function receives the second useReducer parameter as its argument and transforms it into the initial state—giving you control over how that transformation happens while keeping expensive logic lazy.