Preserving and resetting state
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:
Same component, same position → state kept
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
<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:
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:
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:
<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:
// ✗ 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
versionnumber 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:
- Keep everything rendered and hide with CSS — fine for a few small things.
- Lift the state up — store drafts per contact in the parent:
{ ana: 'Hi…', bo: '' }. - Persist it — save drafts to
localStorageor the server. - 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.
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.
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>
);
}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>
))}
{/* A different key = a different editor, so its state starts fresh. */}
<NotesEditor key={course.id} course={course} onSave={onSave} />
</div>
);
}
// Focus is kept because NotesEditor is defined at the top level of the module,
// so it is the same component type on every render.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
keytells React it’s a different instance, resetting its state. - Use
keyto reset forms and editors when the thing they edit changes.