← Back to React, page 2

react-0031 · Medium mid

When does React keep a component's state and when does it reset it? How can you reset state on purpose?

React ties state to a component's position in the tree and its type. If the same component type renders at the same position, state is kept, even when props change. If the type changes, the position disappears, or the key changes, the component unmounts and its state is destroyed. Give a component a key that changes, such as key={userId}, to reset it deliberately. Never define a component inside another one.

Full answer

State is not stored inside the function. React stores it in a tree of fibers, one per component instance, and finds it by position. So the same Profile component at the same spot keeps its state across renders, even if you pass a different user. That surprises people who expect new props to start fresh.

State is kept when the component type and position match the previous render. State is reset when the type at that position changes (a Counter replaced by a Timer), when the component is not rendered for a moment, or when its key changes.

This gives two practical tools. To keep state, render the component in the same place. To reset state, use a key. A form for editing user A that shows user B after navigation should be <EditForm key={user.id} user={user} />. Changing the key tells React "this is a different instance", so it unmounts the old one and mounts a new one. That is cleaner than resetting each field in an effect.

One bug creates state resets by accident: defining a component inside another component. Every render of the outer component creates a new function, so React sees a new type and remounts the inner one, losing state and focus. Define components at module level and pass data through props.

Conditional rendering can also move components. {isAdmin && <Panel />} before a list shifts position in arrays differently than a ternary with null in the same slot. When elements share a position, JSX such as cond ? <A /> : <A /> keeps the same instance because the type and position match. Use keys if you want different instances.

The demo shows an input with no key and one with a key, after switching person.

jsx
import { useState } from 'react';

function Draft({ person, label }) {
  const [text, setText] = useState('');
  return (
    <p>
      <label>
        {label} for {person}: <input value={text} onChange={(e) => setText(e.target.value)} />
      </label>
      <span> draft text: {text}</span>
    </p>
  );
}

export default function App() {
  const [person, setPerson] = useState('Asha');
  return (
    <div>
      <button onClick={() => setPerson('Ravi')}>Switch person</button>
      <Draft person={person} label="Without key" />
      <Draft key={person} person={person} label="With key" />
    </div>
  );
}

The check typed a different draft into each input and then switched the person. The draft without a key stays, although it now belongs to a different person. The draft with key={person} starts empty. Rendered result: <div><button>Switch person</button><p><label>Without key for Ravi: <input value="Asha"></label><span> draft text: Asha</span></p><p><label>With key for Ravi: <input value=""></label><span> draft text: </span></p></div>

Key points

  • State belongs to a component's position in the tree plus its type.
  • Same type at the same position keeps state even if the props change.
  • A different type, a removed component or a different key resets state.
  • Use key={id} to reset a component when its identity changes.
  • Never define components inside other components, since this remounts them every render.

Common mistakes

  • Defining a component inside another component and losing its state on every render.
  • Expecting new props to reset a component's state.
  • Resetting forms by copying props into state and syncing them with effects.
  • Using an index as a key where the item identity changes.

Follow-ups

  • Why does a component defined inside another component lose focus after each keystroke?
  • How does the key trick compare with resetting state inside an effect?
  • What happens to state when a component is hidden with CSS instead of removed?

Tips

  • Say "position and type" in the first sentence. It names the actual rule.
  • Show the key reset as the recommended answer. Many people say "use useEffect".
  • Mention the nested component bug, which is a common review comment.