MyInternships.in

Performance & Patterns

React Keys and Component State Reset

Changing a component’s key tells React to treat it as a different component: it unmounts the old instance and mounts a fresh one with clean state. This is the supported way to reset a subtree deliberately.


What is Keys and Component State Reset in React?

Changing a component’s key tells React to treat it as a different component: it unmounts the old instance and mounts a fresh one with clean state. This is the supported way to reset a subtree deliberately.

Keys and Component State Reset example

Resetting a form when the user changes
JSX
// Without a key, switching users keeps the previous user's typed values.
<ProfileForm key={userId} user={user} />

How this works

The key change makes React discard the old instance entirely, so every useState inside ProfileForm re-initialises from its initial value.

Key points to remember

  • Cheaper and clearer than an effect that resets each field.
  • Also fixes stale scroll positions and animation state.
  • Do not use it on large subtrees you re-key frequently — remounting is not free.

React Keys and Component State Reset— Interview Questions & FAQs

How do I reset a component to its initial state?+

Give it a key that changes when it should reset. React unmounts the old instance and mounts a new one, so all its state starts fresh — no manual reset effect needed.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships