# Complex State with useReducer

> How to manage complex, interconnected state by moving the update logic into a single centralized function.

Subject: React | Lesson 29 of 48 | 5 min read
Interactive lesson: https://codewithanimation.in/react/usereducer
Previous: [Global State Management](https://codewithanimation.in/react/global-state-management.md) | Next: [React.memo](https://codewithanimation.in/react/react-memo.md)

## What is a Reducer?

`useReducer` is an alternative to `useState`. While `useState` is great for simple independent values (like a boolean or a string), `useReducer` is designed for state objects that have multiple properties that update together.

Instead of telling React *what* the new state should be (e.g., `setTasks([...tasks, newTask])`), you tell React *what the user just did* by 'dispatching an action' (e.g., `dispatch({ type: 'added_task', text: 'Buy milk' })`).

A separate function—the 'reducer'—takes that action, applies the logic, and calculates the new state.

## The Spaghettification Problem

Imagine a complex Task Manager component. It needs `tasks` (array), `isEditing` (boolean), `editingId` (number), and `draftText` (string).

If a user clicks 'Edit', you have to call `setIsEditing(true)`, `setEditingId(task.id)`, and `setDraftText(task.text)` all at once.

Your event handlers become bloated with state-updating logic. It's easy to forget one `setState` call and introduce bugs where the UI is in an invalid state (like `isEditing` being true, but `editingId` being null).

## The Three Parts of useReducer

1. **The State:** The data itself.

2. **The Action:** A simple object describing what happened (usually with a `type` string).

3. **The Reducer Function:** A pure JavaScript function that takes `(currentState, action)` and returns the `newState` using a `switch` statement.

Because the reducer is a pure function, you can actually move it completely outside of your component, making it incredibly easy to test independently.

## Common mistake: The Pure Function Rule

A reducer MUST be a pure function. It takes state and an action, and returns a new state object.

It should **never** mutate the existing state directly (e.g., `state.tasks.push(newTask)`). You must always return a brand new object/array.

It should **never** cause side effects. Do not fetch data, do not write to localStorage, and do not call `setTimeout` from inside a reducer.

## Tip: Mental Model

Think of `useReducer` like a strict accountant. You (the UI component) hand the accountant a request form (the Action). The accountant takes the current ledger (the State), follows strict mathematical rules (the Reducer), and hands you back a brand new, updated ledger.

## Try it: The Reducer Pipeline

Interact with the complex state widget below. Watch how UI interactions create 'Action' objects that flow into the centralized Reducer function to calculate the new state tree.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/usereducer

## Check yourself

### Question 1

When is it generally recommended to use `useReducer` over `useState`?

- A. When you are fetching data from an API.
- B. When your state logic is complex, involves multiple sub-values, or when the next state depends heavily on the previous state.
- C. When you want to share state globally across the app.

Correct answer: B

`useReducer` shines when multiple pieces of state need to change simultaneously in response to a single user interaction.

- Why not A: Data fetching is a side-effect, which belongs in `useEffect` or a caching library.
- Why not C: `useReducer` is still local state. Global state requires Context or a library like Zustand.

### Question 2

Which of the following is an INVALID thing to do inside a reducer function?

- A. Using a `switch` statement to check `action.type`.
- B. Returning a brand new object created via the spread operator `...state`.
- C. Making a `fetch()` request to save the new state to the database.

Correct answer: C

Reducers must be pure functions. They calculate the next state, they do not execute side effects like network requests.

- Why not A: This is the standard pattern for reducers.
- Why not B: This is required to maintain immutability.

### Question 3

In the context of `useReducer`, what is an 'Action'?

- A. A plain JavaScript object that describes what happened, typically containing a `type` property.
- B. A callback function passed down to child components.
- C. A React hook used to trigger state updates.

Correct answer: A

Actions decouple *what* happened in the UI from *how* the state should update in response.

- Why not B: While you might pass the `dispatch` function down, the action itself is just an object.
- Why not C: The action is the data passed into the `dispatch` function, not a hook itself.

## Remember this

- `useReducer` centralizes complex state logic into a single function.
- Components 'dispatch actions' instead of calling `setState` directly.
- The reducer is a pure function: `(state, action) => newState`.
- Reducers must NEVER mutate the current state directly.
- Reducers must NEVER contain side effects (like fetching data).
