useReducer
Subject: React
π What is useReducer?
useReducer is a React Hook used to manage complex or structured state logic. Itβs inspired by Redux but built into React β no external library required.
Think of it as a more organized, scalable version of useState when you're dealing with multiple related state values or action types.
π§  When to Use useReducer
| Situation | Use useReducer? | 
|---|---|
| State has multiple sub-values | β Yes | 
| Many types of updates needed | β Yes | 
| Complex state update logic | β Yes | 
| Simple field or counter | β Use useState instead | 
π¦ Syntax
state: Current valuedispatch(action): Function to send an actionreducerFunction: Logic that handles actionsinitialState: Default state value
β
 Example: Counter Using useReducer
π§ Logic Breakdown
- Initial state: 
{ count: 0 } - Clicking a button dispatches an action (e.g. 
{ type: "INCREMENT" }) - Reducer returns new state
 - React re-renders the UI
 
β Example: Form with Multiple Fields
β οΈ Best Practices
| β Do | β Donβt | 
|---|---|
| Keep reducer pure (no side effects) | Don't call APIs or fetch inside reducer | 
Use action.type + optional payload | Avoid deeply nested reducer logic | 
| Group related state together | Don't use for overly simple states | 
Combine with useContext for global use | Donβt repeat reducers in every component | 
π§© Real-Life Use Cases
| Use Case | Why useReducer Works Well | 
|---|---|
| Forms with many fields | One centralized logic for updates | 
| Complex toggles | Combine into one reducer | 
| Game state | Manage scores, levels, status | 
| App-wide global state | Pair with useContext for sharing | 
π§ͺ Bonus: Action Shape
type: describes the actionpayload: data needed to update the state
π Summary Table
| Feature | Description | 
|---|---|
useReducer() | Hook to manage complex or structured state | 
reducer() | Pure function to update state based on action type | 
dispatch() | Function to send action and update state | 
initialState | The default state object or value | 
| Benefit | Clean, scalable, and testable logic | 
π Great next step: Learn how to combine useReducer with useContext for a full app-level state manager.
Advertisement Slot 1
Advertisement Slot 2