Skip to content

Keeping and Resetting State

The Course
•
20 min study

This editor lets you pick a card and change its title. It has a bug that surprises almost everyone the first time.

Edit the selected card React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import CardEditor from "./CardEditor.jsx"; import { starterCards } from "./data.js"; export default function App() { const [cards, setCards] = useState(starterCards); const [selectedId, setSelectedId] = useState(1); const selected = cards.find((card) => card.id === selectedId); function save(id, title) { setCards(cards.map((card) => (card.id === id ? { ...card, title } : card))); } return ( <main> <h1>Study Board</h1> <div className="toolbar"> {cards.map((card) => ( <button key={card.id} onClick={() => setSelectedId(card.id)} aria-pressed={card.id === selectedId}> {card.title} </button> ))} </div> <CardEditor card={selected} onSave={save} /> </main> ); } import { useState } from "react"; export default function CardEditor({ card, onSave }) { const [draft, setDraft] = useState(card.title); return ( <section className="panel"> <h2>Editing card {card.id}</h2> <input aria-label="Title" value={draft} onChange={(e) => setDraft(e.target.value)} />{" "} <button onClick={() => onSave(card.id, draft)}>Save</button> </section> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Predict

The editor shows Read about reducers. Click Practice useState in the toolbar. What will the title field contain?

Check your prediction

It still says Read about reducers, although the heading changed to Editing card 3. Press Save now, and card 3 is renamed to the wrong title.

State belongs to a position in the tree

useState(card.title) uses its argument only on the first render. After that, React keeps the state for as long as the component stays in the same position in the tree. Clicking another card re-renders CardEditor in the same place, with a different card prop, so React keeps the old draft:

JSX
export default function CardEditor({ card, onSave }) {
  const [draft, setDraft] = useState(card.title);

  return (
    <section className="panel">
      <h2>Editing card {card.id}</h2>
      <input aria-label="Title" value={draft} onChange={(e) => setDraft(e.target.value)} />{" "}
      <button onClick={() => onSave(card.id, draft)}>Save</button>
    </section>
  );
}

That's usually what you want. Typing in a field shouldn't be lost because a parent re-rendered. Here, though, a different card should start a fresh draft.

A key resets state

You used keys on Day 4 of the beginner course to tell list items apart. They work on any component. A different key tells React it's a different component, so it throws the old one away, state included, and makes a new one.

In App.jsx, give the editor the card's id as its key:

JSX
<CardEditor key={selected.id} card={selected} onSave={save} />

Now each card gets its own fresh editor, and its draft starts from that card's title. Repeat the experiment.

Two more rules about position

  • Same position, same type: state is kept. Even if you write the component in a different branch of a ternary, {isEditing ? <Editor /> : <Editor />} keeps one state.
  • A different type at that position: state is reset. Swapping <Editor /> for <Preview /> destroys the editor's state, even if you swap back later.

Avoid the alternative

Without a key, you might sync the draft with an effect:

JavaScript
useEffect(() => {
  setDraft(card.title);
}, [card.id]);

It renders once with the stale draft, then again with the right one, and it spreads the "reset when the card changes" rule across two places. The key says it in one word.

Exercise

Keep unsaved drafts separate

With the key in place, start editing card 1, switch to card 2, then back to card 1. Your unsaved change to card 1 is gone. Explain why, then say how you'd keep each card's unsaved draft, without changing what you've learned about keys.

Hint 1: the idea

Keys distinguish component identities; they do not archive state for components that have unmounted.

Hint 2: a first step

The key throws the old editor away, state included. If drafts must survive, where could they live instead?

Show one solution

Switching cards gives the editor a new key, so React destroys it, along with its draft. Coming back makes a brand-new editor whose draft starts from the saved title.

To keep unsaved drafts, lift them out of the editor: store them in App as an object keyed by card id, such as { 1: "Read about reduc", 3: "Practice" }. The editor then receives its draft and an onDraftChange callback as props. State that has to outlive a component lives higher up.

Was this article helpful?

Your response is saved on this device.