A user editor panel lets you choose between three users and edit their name in a form below. Clicking a different user button should reset the form to that user's name, but the input and editing label stay locked on the first user's name no matter which user you select. The bug is rooted in React's state initialization semantics - the value passed to `useState` is only ever used on the component's first mount, so subsequent prop changes have no effect on the existing local state.
Click the Bob button - the input field and the "Editing:" label stay locked on "Alice". Click Carol - still "Alice". Every user button fires correctly but the form never reacts to the user change.
The `name` state initializes correctly the first time - ask yourself what would need to happen for React to run that initialization again.
The `name` state initializes correctly the first time - ask yourself what would need to happen for React to run that initialization again.
Why this fixes it
`useState(user.name)` captures `user.name` as the initial value the moment `ProfileForm` first mounts. After that, React sees `ProfileForm` in the same tree position with the same component type on every re-render and reuses the existing instance - the `useState` initializer never runs again, so the `name` state is permanently locked to whatever the first user's name was. Adding `key={user.id}` to the `<ProfileForm>` element tells React's reconciler that a different `user.id` means a different logical component: React unmounts the old instance entirely and mounts a fresh one, which runs `useState(user.name)` from scratch with the newly selected user's name.