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

Complex State with Multiple Sub-Values

When state is an object with several related fields that change together, useReducer keeps updates cohesive and atomic.

Complex State with Multiple Sub-Values

What you'll learn: How useReducer keeps related state fields synchronized and makes updates atomic when managing objects with multiple properties.

The Problem with Multiple useState Calls

When your component has state that's really an object with several related fields—like a user profile with name, email, and age—you might be tempted to use separate useState hooks for each. But this creates problems: you have to update them separately, they can get out of sync, and related changes require multiple state-setting calls spread across your code.

The useReducer Solution

Think of state as a single cohesive entity. Instead of three separate boxes (nameState, emailState, ageState), you have one box containing a structured object: { name, email, age }. With useReducer, all updates to this object go through one central function (the reducer), ensuring changes happen together atomically.

const [profile, dispatch] = useReducer(profileReducer, {
  name: '',
  email: '',
  age: 0
});

function profileReducer(state, action) {
  switch (action.type) {
    case 'update_name':
      return { ...state, name: action.value };
    case 'update_all':
      return { name: action.name, email: action.email, age: action.age };
    default:
      return state;
  }
}

Now when you need to update multiple fields at once, you dispatch a single action. The reducer ensures the entire state object updates in one atomic operation—no intermediate renders with mismatched data.

Why This Matters

Complex state stays cohesive. You can't accidentally update name without considering email. All transitions live in the reducer, making state changes predictable and easy to trace.

Key Takeaway: When state is an object with multiple related fields, useReducer ensures all updates happen together atomically through a single reducer function, preventing inconsistent intermediate states.