useReducer() Hook in React JS – Example & Explanation
Sridhar Raj P
?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ?? | JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver
useReducer() Hook in React JS – Example & Explanation
The useReducer() hook is an alternative to useState() for managing complex state logic in React functional components. It’s useful when:
Basic Syntax of useReducer()
const [state, dispatch] = useReducer(reducerFunction, initialState);
Example: Counter with useReducer()
We’ll create a simple counter app where:
? + button increases the count
? - button decreases the count
? Reset button resets the count
1. Create Counter.js
import React, { useReducer } from "react";
// Step 1: Define Initial State
const initialState = { count: 0 };
// Step 2: Define Reducer Function
const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
case "RESET":
return initialState;
default:
return state;
}
};
function Counter() {
// Step 3: Use useReducer Hook
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h2>Counter: {state.count}</h2>
<button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
<button onClick={() => dispatch({ type: "RESET" })}>Reset</button>
</div>
);
}
export default Counter;
2. Use Counter in App.js
import React from "react";
import Counter from "./Counter";
function App() {
return (
<div>
<h1>React useReducer Hook Example</h1>
<Counter />
</div>
);
}
export default App;
How It Works