React useReducer Hook
⚙️ React useReducer Hook
The useReducer Hook is an alternative to useState — useful when you have complex state logic or when multiple states depend on each other.
It is commonly used for:
✔ Large or multi-step state updates
✔ Forms
✔ State management patterns (Redux style logic)
✔ Sharing state with Context
🧠 Why useReducer?
useState is great for simple state updates:
But when updates depend on conditions, multiple actions, or complex objects, useReducer is more organized.
🧩 Basic Syntax
– state: Current state
– dispatch: Function to trigger updates
– reducer: Function that controls how state updates
– initialState: Default state value
🧪 Example 1: Simple Counter
🧪 Example 2: Updating Complex State (Object)
🧪 Example 3: Todo List
🔍 When to Use useReducer
Use useReducer instead of useState when:
| Situation | Best Option |
|---|---|
| Simple state | useState |
| Complex state logic | useReducer ✔ |
| Many related values | useReducer ✔ |
| Multiple actions modify state | useReducer ✔ |
| Behavior similar to Redux | useReducer ✔ |
🧠 Summary
| Feature | Description |
|---|---|
Alternative to useState |
✔ |
| Best for complex state | ✔ |
Uses dispatch(action) |
✔ |
| Reducer controls update logic | ✔ |
| Works great with context for global state | ✔ |
