React & Modern Frontend (445 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
How is useReducer Different from useState?
There are notable differences between useState and useReducer hooks.
| Feature | useState | useReducer |
|---|---|---|
| State complexity | Simple (one variable or flat object) | Complex, multi-part or deeply nested |
| Update style | Direct (e.g. setState(x)) | Through actions (e.g. dispatch({})) |
| Update logic | In component | In reducer function |
| Reusability & testing | Less reusable | Highly reusable & testable |
Practical Code Example
jsx
// useReducer vs useState:
// useState: Ideal for independent, simple primitives
const [name, setName] = useState('');
// useReducer: Ideal for complex state machines with interdependent fields
const [state, dispatch] = useReducer(formReducer, { step: 1, isValid: false });