CodeBlanks Logo Icon CodeBlanks

Initial state

Learn the useReducer initial state.

What is initial state?

Initial state is the second parameter of useReducer; it is the starting value of state. When you write useReducer(reducer, initialState), on the first render state takes this value.

Initial state is often an object; for example { count: 0, name: "" }. But it can also be a number, string or array. Sometimes you want to compute initial state through a function; in that case useReducer(reducer, initialArg, init) takes an init function as the third parameter. This is used to run the initial value through an expensive operation. In most cases the second parameter is enough.

An object initial state

In some apps state has several fields. In that case initial state is an object. Example: { count: 0, max: 10 }. When the reducer returns a new object on each action it must keep the other fields.

This requires the spread pattern: return { ...state, count: state.count + 1 }. Here ...state opens the existing fields and count takes its new value. So the max field stays unchanged. A reducer never mutates the current state directly; it always returns a new object. This approach makes state changes traceable.

Practice A reducer with object state

Write a reducer. state is an object: { count: 0 }. With switch (action.type) return { ...state, count: state.count + 1 } in the "increment" case. In the default branch return state.

Starter code

App.js
// Write a reducer function
// state is an object: { count: 0 }
// Use switch on action.type; write increment and default branches

Sample solution

App.js
function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the second parameter of useReducer?

App.js
useReducer(reducer, initialState);
  • dispatch
  • reducer
  • initialState Correct answer
  • action

Explanation: The second parameter is initialState.

2 Update with spread

Question
return { ____, count: state.count + 1 };
Answer
return { ...state, count: state.count + 1 };

Explanation: ...state copies existing fields into the new object.

3 Match the concept to its role

Term Meaning
initialState Starting value
useReducer Hook call
reducer Computes state
object state Several fields

All lessons in Intermediate