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)