Chapter 10 ยท Managing State
Preserving State & Reducers
When does React keep state, and when does it throw it away? And how do you tidy up complicated update logic?
- Why state is tied to a component's position in the tree
- When React keeps or resets state
- How to force a reset with
key - How to move update logic into a reducer with
useReducer
Part A ยท Preserving and resetting state
State lives at a position in the tree
You might think state lives "inside" a component. Actually React holds it, and attaches it to the component's position in the UI tree.
Each <Counter /> is at a different position, so each has separate state. If you stop rendering a component, React destroys its state. Render it again later, and it starts fresh.
Same component at the same position โ state is kept
Toggling isFancy does not reset the count. Either way it's a Counter in the same spot, so React treats it as the same component with new props.
Different component at the same position โ state is reset
Switching from Counter to <p> removes the Counter and its state. The same happens if the parent element changes type (for example <div> โ <section>): the whole subtree is reset.
MyTextField function. React sees a different component at that position and resets its state, so the input loses its text every time the parent re-renders.
Resetting state on purpose with key
Sometimes you want a reset. Example: a chat app where the draft message should clear when you switch contacts.
A key tells React "this is a different chat when the key changes". When contact.id changes, React throws away the old Chat (including its draft) and makes a fresh one.
Part B ยท Extracting state logic into a reducer
When a component has many event handlers that all update the same state in different ways, the logic gets scattered. A reducer gathers it all into one function, outside the component.
Before: logic spread across handlers
Step 1: handlers dispatch actions
Instead of saying how to update the state, handlers describe what the user just did, as an action object:
Step 2: write the reducer function
A reducer takes the current state and an action, and returns the next state:
Step 3: use it in your component
reduce(), which takes "the result so far + the next item" and returns the new result. A React reducer takes "the state so far + the next action" and returns the new state.
useState vs useReducer
useState | useReducer | |
|---|---|---|
| Code size | Less code for simple state | More code up front |
| Readability | Great for simple updates | Better when there are many kinds of update |
| Debugging | Harder to see why state changed | Log each action in one place |
| Testing | Tied to the component | The reducer is a plain function, easy to test |
- They must be pure: no fetches, timers or mutations. Just calculate the next state.
- Each action should describe one user interaction (
'reset_form'), even if it changes several fields.
More examples
Example 1: hiding vs removing
Choose deliberately: removing gives a fresh start, while hiding keeps whatever the user entered.
Example 2: the same position, so state is shared by accident
Example 3: a reducer for a form
Example 4: logging every action (easy debugging)
Example 5: testing a reducer without React
Recap
- React keeps state as long as the same component is rendered at the same position.
- A different component type at that position, or a removed component, means the state is reset.
- Change the
keyto force a reset. Never define components inside other components. useReducer(reducer, initial)moves update logic into one pure function. Handlersdispatchactions that describe what happened.
Exercises
1. Reset the form
A ContactForm keeps a message draft in its own state. When the user picks a different contact, the old draft stays. Fix it with one small change in the parent.
Show solution
2. Counter with a reducer
Rewrite a counter (+, โ, reset) using useReducer with actions increment, decrement and reset.
Show solution
3. Predict the reset ๐ข easy
For each case, does the Counter's count survive when flag toggles?
Show answer
A: kept (same component, same position). B: reset (the Counter is removed). C: reset (the parent type changed from div to section). D: reset (different keys).
4. Keep the draft while hidden ๐ข easy
A "Hide editor" button removes an editor with {show && <Editor />}, and the text is lost each time. Change it so the text survives.
Show solution
Alternatively, lift the text state up into the parent, so it doesn't matter whether Editor is mounted.
5. Fix the disappearing text ๐ข easy
Typing works, but clicking the button erases the text. Why? Fix it.
Show solution
NameInput is defined inside App, so every render creates a new component type and resets its state. Move it to the top level:
6. Separate drafts per contact ๐ก medium
In a chat app, you want to keep a separate draft for each contact, so switching back shows what you typed earlier. A key alone resets the draft. How would you keep them?
Show solution
Lift the drafts up into an object keyed by contact ID:
7. Light switch reducer ๐ข easy
Write lightReducer(state, action) for { on: false, brightness: 50 }, with the actions toggled, brighter (+10, max 100) and dimmer (โ10, min 0).
Show solution
8. Todo reducer ๐ก medium
Convert your todo app from Chapter 8 to useReducer, with the actions added, toggled, deleted and cleared_completed.
Show solution
Note that the ID is generated in the handler, not in the reducer, because reducers must be pure.
9. Test your reducer ๐ก medium
Write three console.assert checks for todosReducer: adding, toggling, and clearing the completed todos.
Show solution
10. Cart reducer ๐ด hard
Write cartReducer with these actions: added (if the product is already in the cart, increase its qty), removed, quantity_changed (remove the item if qty โค 0) and cleared. Show the total price as a derived value in the component.
Show solution
๐ Official docs: Preserving and Resetting State ยท Extracting State Logic into a Reducer