Key prop

2 snippets in React

REReact

Key Prop for Efficient Updates

RE · Performance
syntax
// Stable keys help React identify which items changed
<Item key={item.id} />

// Reset component state by changing the key
<Form key={selectedUserId} />
example
// Using key to reset component state
function UserEditor({ userId }) {
  // When userId changes, React destroys the old Form
  // and mounts a fresh one with clean state
  return <ProfileForm key={userId} userId={userId} />;
}

function ProfileForm({ userId }) {
  const [name, setName] = useState('');
  const [bio, setBio] = useState('');

  useEffect(() => {
    fetchUser(userId).then(user => {
      setName(user.name);
      setBio(user.bio);
    });
  }, [userId]);

  return (
    <form>
      <input value={name} onChange={e => setName(e.target.value)} />
      <textarea value={bio} onChange={e => setBio(e.target.value)} />
    </form>
  );
}

Note Changing a component's key forces React to unmount and remount it, resetting all internal state. This is a clean way to 'reset' a form or component when switching between items without manually clearing each state variable.

Missing or Bad Keys

RE · Common Mistakes
syntax
// BAD: index as key with reorderable list
{items.map((item, i) => <Item key={i} />)}

// GOOD: stable unique identifier
{items.map(item => <Item key={item.id} />)}
example
// BUG: using index as key with a removable list
function BrokenList() {
  const [items, setItems] = useState([
    { id: 'a', text: 'First' },
    { id: 'b', text: 'Second' },
    { id: 'c', text: 'Third' },
  ]);

  function removeFirst() {
    setItems(prev => prev.slice(1));
  }

  return (
    <div>
      {/* Using index: after removing first item,
         React thinks items shifted, inputs lose state */}
      {items.map((item, index) => (
        <div key={index}>
          <input defaultValue={item.text} />
        </div>
      ))}
      <button onClick={removeFirst}>Remove First</button>
    </div>
  );
}

// FIX: use item.id as key
// {items.map(item => <div key={item.id}>...)}

Note Index keys cause broken behavior when items are added, removed, or reordered. React associates state (including uncontrolled input values) with the key. When keys shift, state gets attached to the wrong item.