As React applications grow, managing complex state using useState becomes difficult. When state logic depends on multiple conditions or actions, React provides a better solution called useReducer.
🔹 What is useReducer?
useReducer is a React Hook used to manage complex state logic in a predictable way.
In simple words:
useReducer is an alternative to useState when state updates are complex or related.
🔹 When should you use useReducer?
Use useReducer when:
State depends on previous state
Multiple actions modify the same state
Logic becomes messy with many useState calls
❌ Too many useState
useState(count)
useState(error)
useState(loading)
✅ One useReducer
useReducer(reducer, initialState)
🔹 Basic Syntax of useReducer
const [state, dispatch] = useReducer(reducer, initialState);
state → current state
dispatch → function to send actions
reducer → function that updates state
🔹 Simple Example: Counter using useReducer
1️⃣ Reducer Function
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
}
2️⃣ Component
import { useReducer } from "react";
const initialState = { count: 0 };
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
dispatch({ type: "INCREMENT" })}>+
dispatch({ type: "DECREMENT" })}>-
</>
);
}
🔹 How useReducer Works (Logic)
Component dispatches an action
Reducer receives current state and action
Reducer returns a new state
React updates UI automatically
🔹 Why Reducer Must Be Pure?
A reducer:
❌ Should not modify state directly
❌ Should not call APIs
✅ Should return new state only
This makes state changes predictable and debuggable.
Top comments (0)