React Best Practices

Chapter 2 · Practice 4 of 5

Reset a component's state by changing its key

From State and data flow

Why it matters

Sometimes a component should start fresh for a new item, such as a comment box when you switch to another user's profile. Give it a key tied to that item.

Changing the key tells React it is a different component, so all state inside it is recreated.

This is simpler and more correct than an effect that clears state when a prop changes:

  • The key version renders once, with fresh state.
  • The effect version renders once with stale values and then again with the cleared ones, which can flash old data on screen.

Example

TSX
function ProfilePage({ userId }: { userId: string }) {
  // All state inside Profile resets when userId changes
  return <Profile key={userId} userId={userId} />;
}