useState in Complex ScenariosFor simple, isolated pieces of state (like toggling a boolean, incrementing a counter, or holding text in an input), useState is clean and sufficient.
However, as applications grow, you frequently encounter state logic where:
idle -> fetching -> success or error).In these scenarios, managing state through disjointed useState setters causes synchronization bugs, race conditions, and messy code.
The solution is the useReducer hook.
useReducer?useReducer is an alternative to useState modeled after Redux and functional programming state machines.
Instead of calling setter functions directly, components dispatch actions (plain JavaScript objects describing what happened). A centralized, pure function called the reducer receives the current state and the action, and computes the next state:
$$\text{NextState} = \text{reducer}(\text{CurrentState}, \text{Action})$$
useState vs useReducer in CodeuseState (Scattered, Fragile):useReducer (Centralized, Predictable):useState vs useReducer| Criterion | useState | useReducer |
|---|---|---|
| Data Structure | Primitives, independent values | Complex objects, nested arrays |
| Transition Complexity | Simple (direct assignment) | Complex business logic, state machines |
| State Dependencies | Next state is independent | Next state depends on multiple fields |
| Testability | Harder to test isolated logic | Trivial: Reducer is a pure JS function! |
| Code Organization | Setters scattered in handlers | Logic centralized in one place |
useReducer hook in React?useReducer over useState?useReducer hook return when invoked?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Context Performance and Preventing Render Cascades | Reducer Functions, Actions, and Dispatch |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.