hardFrontend

How can the `key` prop be used to deliberately reset component state?

877 views
01

Understand the problem

Remounting via key changes instead of syncing props to state.

reactreconciliationstate
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Explore the playground snippets

Changing key remounts and resets state
Run Playground
import { useState } from 'react';

function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN((x) => x + 1)}>Clicked {n} times</button>;
}

export default function App() {
  const [id, setId] = useState(0);
  return (
    <div style={{ fontFamily: 'sans-serif', padding: 24 }}>
      <Counter key={id} />   {/* changing the key remounts -> state resets to 0 */}
      <div style={{ marginTop: 12 }}>
        <button onClick={() => setId((i) => i + 1)}>Reset (change key)</button>
      </div>
      <p style={{ color: '#666' }}>Click a few times, then Reset — the fresh Counter starts at 0.</p>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.