Create a counter component using useReducer in React
Understand how to manage counter logic using useReducer for more controlled and predictable state transitions.
Question
Create a counter component using useReducer in React.
Answer
useReducer is a React hook used to handle complex state logic. Instead of calling setState directly, you dispatch actions to a reducer function.
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 };
case 'reset':
return { count: 0 };
default:
return state;
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
}
✅ useReducer gives predictable updates and scales better for complex logic.
Real-World Example
Used in:
- Shopping cart quantity
- Score tracking
- Multi-step forms
Quick Practice
Add a "bonus" action that increases count by 5 when triggered.
Summary
useReducer replaces messy state updates with a clean, action-driven flow for more predictable state management.
Why use useReducer over useState?
When your state transitions have multiple actions or depend on previous values, useReducer provides structure and clarity.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.