useReducer — Complete Guide
useReducer — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.
On this page
React.js Tutorial · Lesson 27 of 100
useReducer
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Learn by example · ~6 min · Module 3: Forms & Hooks
What is this?
useReducer manages complex state with a reducer function: (state, action) => newState. Like useState but better when updates follow clear action types.
Why should you care?
Forms with many fields, wizards, and shopping carts often have predictable update rules — dispatch({ type: "ADD_ITEM", payload }) keeps logic in one place.
See it live — copy this example
Paste into src/App.jsx (or the file noted in the steps). Save and watch the browser update.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
Run Example »
Edit the code and click Run to see the result update live.
What happened?
- All update logic lives in reducer.
- Components only dispatch actions.
- Easier to test reducer in isolation.
Try it yourself
- Define action types as strings or constants.
- Write reducer with switch or if.
- Replace multiple related useState with one useReducer.
- Change text or labels in the example and save — watch the browser update.
- Break the code on purpose (remove a bracket), read the error message, then fix it.
Remember
useReducer(reducer, initialState) → [state, dispatch]. Good for complex state transitions. Keep reducer pure — no side effects inside.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!