AZ.dev

Reset a component's state when the thing it shows changes

| react: 16+

Give the component a key tied to its subject. When the key changes, React unmounts the old instance and mounts a new one, so every useState inside starts fresh.

<Editor key={docId} doc={doc} />

Switch from document 12 to document 13 and the editor’s draft text, its dirty flag and its scroll position all reset, with no code inside Editor knowing about it.

The alternative, and why it loses

The other option is an effect that watches the prop and resets state by hand:

useEffect(() => {
  setDraft(doc.body);
  setDirty(false);
}, [doc.id]);

That renders once with stale state, then again with the reset, and it has to name every piece of state. Add a new useState next year and forget to add it here, and the bug is back. The key does all of it in one render.

When a key is the wrong tool

Gotchas

key state reset remount forms

This entry is one card on a printable cheat sheet:

React Essentials Cheat Sheet

Was this helpful?

Related Entries

Update state from its previous value without losing updatesWhy useEffect runs twice in development and how to write it so that's fine