Resetting Controlled Components in Forms
PublishedLast updated
If you're starting to leverage some of React's form primitives (e.g. action
/ formAction
and Server Actions), you might run into the same conundrum I did with controlled components.
By default, React will reset a form after a submission [1], however that doesn't really do much to components that manage their own state, the state managed by React will be preserved on the form submit.
This could lead to possibly weird looking form states after submission, or even bugs with previous values being submitted the next time a form is submitted.
However, there's a really neat way to hook into this automatic form reset behavior within your controlled component, and thats by adding a reset event handler!
Here's a small snippet of a controlled component:
When this is used within a form that is submitted, the inputValue
and selected
state values will be preserved, meaning the MultiSelect will probably show you the values instead of an empty state.
The neat way to handle this reset behavior is to add an event listener:
And that's it! React, under the hood, effectively calls formElement.reset()
which will trigger our event listener and clear our managed state!