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?

You will learn
  • 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.

What matters React cares about the position in the returned JSX tree, not where the code sits in your function.

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.

โŒ This is why you never define components inside components Every render creates a different 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

Why is it called a "reducer"? It's named after the array method 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

useStateuseReducer
Code sizeLess code for simple stateMore code up front
ReadabilityGreat for simple updatesBetter when there are many kinds of update
DebuggingHarder to see why state changedLog each action in one place
TestingTied to the componentThe reducer is a plain function, easy to test
Rules for reducers
  • 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 key to force a reset. Never define components inside other components.
  • useReducer(reducer, initial) moves update logic into one pure function. Handlers dispatch actions 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