Preserving and resetting state

Topic 3 of 4 in Managing state7 min readIntermediateFree course

Overview

You learned that each component instance has its own state. But when does React keep that state, and when does it throw it away? The answer explains several puzzling bugs — inputs that keep stale text, or forms that mysteriously reset — and gives you a clean tool for resetting state on purpose.

State is tied to a position in the tree

React doesn’t store state “inside” your component function. It stores it alongside the component’s position in the UI tree. When React re-renders, it walks the new tree and compares each position with the previous render:

Three cases. Same component in the same spot: Counter then Counter — state kept. Different component in the same spot: Counter then a p element saying Paused — state destroyed. Same component with a new key: Chat key ana then Chat key bo — state reset.

Same component, same position → state kept

JSX
function Scoreboard({ isFancy }) {
  return (
    <div>
      {isFancy ? <Counter isFancy={true} /> : <Counter isFancy={false} />}
    </div>
  );
}

Toggling isFancy doesn’t reset the counter. Both branches render a <Counter> as the first child of the <div>, so from React’s point of view it’s the same counter with a changed prop. It doesn’t matter that they come from different lines of code — React only sees the resulting tree.

Different component, same position → state destroyed

JSX
<div>
  {isPaused ? <p>See you later!</p> : <Counter />}
</div>

When isPaused becomes true, a <p> replaces the <Counter>. React unmounts Counter and destroys its state. When you switch back, a brand-new Counter starts at 0.

This also applies to the wrapper elements: if <div><Counter /></div> becomes <section><Counter /></section>, the whole subtree is recreated, and Counter loses its state — even though Counter itself didn’t change.

Why nested component definitions break state

This is the reason behind the “never define components inside components” rule from Your first component:

JSX
function SignupForm() {
  const [email, setEmail] = useState('');

  // ✗ A new EmailInput function is created on every render
  function EmailInput() {
    return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
  }

  return <EmailInput />;
}

Each keystroke updates email, SignupForm re-renders, and a new EmailInput function is created. A different function is a different component type, so React throws away the old <input> and creates a new one — and the input loses focus after every character. Move EmailInput to the top level and pass email and setEmail as props.

Resetting state on purpose with key

Sometimes you want a fresh start. Consider a chat app:

JSX
function Messenger() {
  const [contact, setContact] = useState(contacts[0]);
  return (
    <>
      <ContactList contacts={contacts} onSelect={setContact} />
      <Chat contact={contact} />
    </>
  );
}

function Chat({ contact }) {
  const [text, setText] = useState('');
  return <textarea value={text} placeholder={`Message ${contact.name}`} onChange={(e) => setText(e.target.value)} />;
}

Type a message to Ana, switch to Bo, and your half-written message to Ana is still in the box, ready to be sent to the wrong person. Chat is at the same position with the same type, so React preserves its state.

Give it a key:

JSX
<Chat key={contact.id} contact={contact} />

Keys aren’t just for lists. A key tells React which instance this is. When the key changes from ana to bo, React treats it as a completely different component: it unmounts the old Chat (discarding its state) and mounts a new one.

This is the idiomatic way to reset state — much simpler and less error-prone than an effect that watches a prop and clears state:

JSX
// ✗ Avoid: resetting state in an effect renders twice and is easy to get wrong
useEffect(() => {
  setText('');
}, [contact.id]);

// ✓ Prefer: a key
<Chat key={contact.id} contact={contact} />

Common uses for key resets

  • Edit forms: <CourseForm key={course.id} course={course} /> — each course gets fresh form fields.
  • Profile pages: <Profile key={userId} userId={userId} /> — no flash of the previous user’s data in local state.
  • “Start over” buttons: keep a version number in state, render <Quiz key={version} />, and increment it to reset everything inside.

Keeping state for hidden components

What if you want to preserve the state of something that disappears — the draft for each contact, or a tab’s scroll position? Options:

  1. Keep everything rendered and hide with CSS — fine for a few small things.
  2. Lift the state up — store drafts per contact in the parent: { ana: 'Hi…', bo: '' }.
  3. Persist it — save drafts to localStorage or the server.
  4. Use <Activity mode="hidden"> — React keeps the hidden subtree’s state while it’s not visible (covered in Code splitting and Activity).

Summary of the rules

Situation What happens to state
Same type, same position, new props kept
Different type at that position destroyed (whole subtree)
Parent wrapper element changes type destroyed (whole subtree)
Component function recreated every render destroyed every render
Same type, different key reset

Mental model: React asks two questions at each position — “is it the same type?” and “is it the same key?” If both answers are yes, the state survives.

Exercise

Reset the editor when switching courses

A CourseEditor lets you pick a course from a list on the left and edit its notes in a NotesEditor with its own draft state. Bug: when you switch to another course, the draft from the previous course stays in the textarea. Fix it without an effect, so each course starts with its own saved notes. Then make sure typing in the editor doesn’t lose focus as the parent re-renders.

JavaScript
import { useState } from 'react';

function NotesEditor({ course, onSave }) {
  const [draft, setDraft] = useState(course.notes);
  return (
    <>
      <textarea aria-label="Notes" value={draft} onChange={(e) => setDraft(e.target.value)} />
      <button onClick={() => onSave(course.id, draft)}>Save</button>
    </>
  );
}

export function CourseEditor({ courses, onSave }) {
  const [selectedId, setSelectedId] = useState(courses[0].id);
  const course = courses.find((c) => c.id === selectedId);

  return (
    <div>
      {courses.map((c) => (
        <button key={c.id} onClick={() => setSelectedId(c.id)}>{c.title}</button>
      ))}
      <NotesEditor course={course} onSave={onSave} />
    </div>
  );
}

Summary

  • React keeps state as long as the same component type is rendered at the same position in the tree.
  • Rendering a different component type at that position destroys the old state, including all state below it.
  • Components defined inside other components are new types every render, so their state is always lost.
  • Changing a component’s key tells React it’s a different instance, resetting its state.
  • Use key to reset forms and editors when the thing they edit changes.