useReducer and custom hooks
Two tools for keeping components clean as logic grows: useReducer, which centralises complex state updates, and custom hooks, which extract reusable stateful logic.
When useState gets messy
Lots of related state updated from many handlers, often several pieces at once, is a sign you want a reducer.
useReducer
A reducer is a pure function: (currentState, action) => newState. Components dispatch actions that describe what happened, and the reducer decides how the state changes:
Benefits:
- All update logic lives in one place, so it's easy to read and to test (the reducer is a plain function).
- Handlers just say what happened:
dispatch({ type: 'added', product }). - It pairs beautifully with TypeScript discriminated unions for the action types.
Custom hooks: reuse stateful logic
A custom hook is a function whose name starts with use and which calls other hooks. It lets you share logic (not UI) between components:
Each component that calls a custom hook gets its own independent state. Hooks share logic, not data.
Custom hook for data fetching
Libraries like TanStack Query are essentially very polished versions of useFetch, with caching, retries and refetching built in.
Practice
- Write
useCounter(initial, { min, max }), which returns{ count, increment, decrement, reset }and respects the bounds. - Convert the to-do list from the Lists lesson to
useReducer, with actionsadded,toggled,deletedandclearedCompleted.
1.What must a reducer function be?
2.Two components call the same custom hook useToggle(). Do they share state?