What Is useReducer?
The useReducer hook is an alternative to useState for managing complex state logic.
It uses a reducer function to update state based on actions.
Basic Syntax
const [state, dispatch] = useReducer(reducer, initialState);
reducer(state, action)→ returns new statedispatch(action)→ triggers state update
Example: Counter Using useReducer
import React, { useReducer } from "react";
const initialState = { count: 0 };
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 App() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h2>Count: {state.count}</h2>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);
}
export default App;
✅ State updates are handled via dispatch with action objects.
Key Points
- Ideal for complex or nested state
- State updates are predictable using reducer logic
- Works well with multiple related actions
- Similar to Redux reducer concept
Conclusion
useReducer helps manage complex state efficiently in functional components and keeps state logic centralized.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP