I occasionally have react components that are conceptually stateful which I want to reset. The ideal behavior would be equivalent to removing the old component and readding a new, pristine component.
React provides a method setState
which allows setting the components own explicit state, but that excludes implicit state such as browser focus and form state, and it also excludes the state of its children. Catching all that indirect state can be a tricky task, and I'd prefer to solve it rigorously and completely rather that playing whack-a-mole with every new bit of surprising state.
Is there an API or pattern to do this?
Edit: I made a trivial example demonstrating the this.replaceState(this.getInitialState())
approach and contrasting it with the this.setState(this.getInitialState())
approach: jsfiddle - replaceState
is more robust.
To reset a component to its initial state:Store the initial state in a variable. When an event occurs, call the setState() function, passing it the initial state.
The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).
React gives us two options in which we can reload a component. Either we can reload a component using the Vanilla JavaScript , or we can use the state to reload the component whenever a change is made in the state of that component.
To ensure that the implicit browser state you mention and state of children is reset, you can add a key
attribute to the root-level component returned by render
; when it changes, that component will be thrown away and created from scratch.
render: function() { // ... return <div key={uniqueId}> {children} </div>; }
There's no shortcut to reset the individual component's local state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With