State Management · Middle · Question 2 of 75
How do you reset a form component's state when the selected user changes?
- ✓Correct answer: Render it with
key={userId}so React recreates the component - 2Reset every field in a
useEffectthat depends onuserId - 3Call
setState(undefined)to reset the state to its initial value
Explanation
A different key makes React treat it as a new component: old state is dropped and the initial values apply. A resetting effect first renders stale data and then fixes it - an extra render and a visible flash.