State Management (useReducer)
Definition
The `useReducer` hook is an alternative to `useState`. It is usually preferable when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. It uses the Redux pattern of dispatching 'actions' to a 'reducer' function.
Explain Like I'm New
Imagine managing a bank account. You don't just say 'Set my balance to $500' (`useState`). Instead, you go to the teller (the Reducer) and hand them an instruction slip (the Action) that says 'DEPOSIT $100'. The teller looks at the slip, checks the rules, and updates the vault safely. `useReducer` centralizes all the complex rules for how state can change into one single function.
Real World Example
Managing a complex Shopping Cart. Instead of having separate `useState` calls for items, total price, and discount codes, you use a single reducer that handles actions like 'ADD_ITEM', 'REMOVE_ITEM', and 'APPLY_DISCOUNT'.
Common Use Cases
- •Managing complex state objects or arrays
- •When next state depends heavily on previous state
- •Moving heavy business logic out of the component and into a separate function
Interactive Example
Interview Questions
basic
- What arguments does `useReducer` take?
- What does the `dispatch` function do?
intermediate
- When should you choose `useReducer` over `useState`?
- What is an 'action' object usually composed of?
advanced
- Why must a reducer function be 'pure'?
- How does `useReducer` help avoid passing callbacks deeply through components?
trick
- Can a reducer function trigger an API call (side effect)?