Q39: How do you force a complete component state reset using the key prop?

Passing a different key attribute value to a component forces React to treat it as a brand-new component instance. React unmounts the old instance, destroys its local state completely, and mounts a fresh instance with initial state.

Resetting Form Component State via Key Change
function UserProfileContainer({ userId }) {
  // Changing userId key forces UserForm to reset internal form state completely
  return <UserForm key={userId} userId={userId} />;
}

When userId changes, React unmounts old UserForm and initializes a clean form instance.

Key Takeaways
  • Changing key values forces full component instance teardown and state reset.

  • Cleaner pattern than writing manual reset useEffect handlers.

Knowledge Check

What happens to a child component's internal useState variables when its parent changes its key prop from 'A' to 'B'?