Hello! Let's dive into our next lesson on advanced state management in React.
In our previous lessons, we've seen how to create and consume global state using the Context API, managing the provider's state with a simple useState hook. This is effective for straightforward values like a theme preference. However, as applications grow, state logic can become much more intricate. What if updating one piece of state requires complex calculations or needs to trigger updates in several other related pieces of state? Managing this with multiple useState hooks can become messy and error-prone.
Today, we will address this challenge by exploring a powerful alternative. Our learning goal is to introduce the useReducer hook for managing complex state transitions. You'll learn what a reducer is, why it's beneficial for complex state, and how to implement it in a React component with TypeScript.
1. The Problem: When useState Isn't Enough
Imagine you're building a component that fetches data from an API. You need to manage several related pieces of state:
- Is the data currently loading? (
isLoading: boolean) - Did an error occur? (
error: string | null) - What is the fetched data? (
data: T | null)
Managing this with multiple useState hooks looks like this:
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<MyDataType | null>(null);
When you start fetching, you need to set isLoading to true and error to null. When the fetch succeeds, you set isLoading to false and update data. If it fails, you set isLoading to false and update error. You're frequently setting multiple state variables together, and the logic for these transitions is scattered throughout your component's event handlers and effects. This can be hard to read and maintain.

This is precisely the kind of scenario where useReducer provides a cleaner, more organized solution.
Managing Complex State in React with useReducer
To see a detailed example of this problem, let's look at an article from Aleksandr Hovhannisyan's blog. It sets up a realistic scenario involving fetching paginated image results and highlights the challenges of coordinating multiple useState hooks.
Please read the first section, "Problem: Managing Complex State with useState". Focus on how changing the search query requires manually resetting multiple state variables (setImages, setTotalPages), and how this approach is not scalable.
In summary, useReducer is often preferable to useState when:
- Your state is an object with several interdependent properties.
- State transitions are complex and involve logic that goes beyond a simple
setNewValue(). - You want to co-locate all your state update logic in a single, predictable place outside of your component.
2. The Anatomy of useReducer
The useReducer hook is built around a pattern common in functional programming and popularized by libraries like Redux. It separates the what from the how. Instead of directly telling React what the new state is, you dispatch an action that describes what just happened. A function called a reducer then handles this action and computes the new state.
There are four key parts to this pattern:
- State: The data object your component manages.
- Action: An object that describes a state change. By convention, it has a
typeproperty (e.g.,'increment') and an optionalpayloadwith data. - Reducer: A pure function that takes the current
stateand anactionas arguments and returns the new state. It's the central hub for all your state logic.(currentState, action) => newState - Dispatch: A function provided by the
useReducerhook that you call to send (or "dispatch") an action to the reducer.
This diagram illustrates the flow:

The useReducer Hook Signature
In your component, you call useReducer like this:
const [state, dispatch] = useReducer(reducer, initialState);
reducer: The reducer function you'll write.initialState: The initial value of your state object.- It returns an array with two elements:
state: The current state value.dispatch: The function you use to trigger state updates by sending actions.
3. Implementing useReducer: A Step-by-Step Example
Let's see this in action by building a simple counter component. While a counter can be easily built with useState, we'll add some complexity to demonstrate the power of useReducer.
Learn React Hooks: useReducer - Simply Explained!
This video from Cosden Solutions provides an excellent, concise walkthrough of implementing useReducer from scratch with TypeScript. We will follow its structure to build our understanding.
Please watch from 00:55 to 07:57. This segment will guide you through: The basic concept and syntax of useReducer. Defining basic TypeScript interfaces for the State and Action. Writing the reducer function using a switch statement. Calling useReducer in the component and using dispatch in event handlers.
Let's recap the key code structures from the video.
First, you define the shapes of your state and actions with TypeScript:
// Define the shape of the state object
interface State {
count: number;
error: string | null;
}
// Define the shape of the action object
// The 'type' is a union of specific string literals
interface Action {
type: 'increment' | 'decrement';
}
Note: This simple Action interface works well for actions without data. In the next lesson, we'll explore a more powerful pattern for this called "discriminated unions."
Next, you write the reducer function, which contains all the update logic:
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'increment':
// Always return a *new* state object
return { ...state, count: state.count + 1 };
case 'decrement':
return { ...state, count: state.count - 1 };
default:
return state;
}
}
Finally, you use it in your component:
const initialState: State = { count: 0, error: null };
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
{/* Dispatch actions on user events */}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}
4. The Real Power: Managing Complex Transitions
So far, this might seem like a lot of boilerplate for a simple counter. The true benefit emerges when the state logic becomes more complex. Let's add a rule: the count cannot go above 5 or below 0. If a user tries, we should show an error message.
With useState, you'd need a separate error state, and your onClick handlers would contain if/else logic to update both the count and the error. With useReducer, all of this logic can be cleanly handled inside the reducer.
Learn React Hooks: useReducer - Simply Explained!
Let's continue with the same video, which now demonstrates exactly how to handle this more complex logic.
Watch the segment from 09:20 to 12:25. Pay close attention to how the reducer is modified. Notice that for a single 'increment' action, the reducer can now conditionally update both the count and the error fields, all in one predictable place.
The updated reducer logic looks something like this:
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'increment': {
const newCount = state.count + 1;
const hasError = newCount > 5;
return {
...state,
count: hasError ? state.count : newCount, // Only update count if no error
error: hasError ? 'Maximum reached' : null, // Set or clear error
};
}
case 'decrement': {
const newCount = state.count - 1;
const hasError = newCount < 0;
return {
...state,
count: hasError ? state.count : newCount,
error: hasError ? 'Minimum reached' : null,
};
}
default:
return state;
}
}
Notice how clean this is. The component's only job is to dispatch({ type: 'increment' }). It doesn't need to know about the validation rules. All the complex logic is encapsulated and co-located within the reducer, making it easy to understand, test, and debug.
Test your understanding!
Let's add a 'reset' feature to our counter. Your task is to modify the reducer to handle a new action.
- Add
'reset'to theActioninterface'stypeunion. - Add a new
caseto thereducer'sswitchstatement for the'reset'action. - This action should reset the
countto0and clear anyerrormessage (set it tonull).
How would you implement this?
Show answer
First, update the Action type:
interface Action {
type: 'increment' | 'decrement' | 'reset'; // Added 'reset'
}
Next, add the new case to the reducer:
function reducer(state: State, action: Action): State {
switch (action.type) {
// ... increment and decrement cases
case 'reset': {
return {
...state,
count: 0,
error: null,
};
}
default:
return state;
}
}
Now, you can add a button in your component that calls dispatch({ type: 'reset' }) to trigger this logic.
Conclusion
You've just learned the fundamentals of one of React's most powerful hooks for state management. By centralizing update logic, useReducer makes your components more predictable and maintainable as they grow in complexity.
Key Takeaways:
useReduceris a hook for managing state, particularly beneficial when the state is complex or involves interdependent variables.- It separates the description of a state change (action) from the implementation of that change (reducer).
- The reducer is a pure function that takes the current
stateand anactionand returns a new state. This makes your state logic predictable and easy to test. - The dispatch function is used to send actions from your component to the reducer, triggering a state update.
- This pattern co-locates all state transition logic, making your components cleaner and your state management more robust.
Preview of the Next Lesson:
In this lesson, our actions were simple objects with only a type. But what if an action needs to carry data, like a user's input from a form? To handle this with full type safety, we need a more advanced TypeScript pattern. In the next lesson, we will learn how to define types for useReducer state and actions using discriminated unions, which will unlock powerful autocompletion and error-checking in your reducers.