Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reset a react component including all transitively reachable state?

Tags:

reactjs

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.

like image 456
Eamon Nerbonne Avatar asked Feb 13 '14 09:02

Eamon Nerbonne


People also ask

How do I reset a component in React?

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.

How do you reset all input field in React?

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' }) ).

Can we refresh a component in React?

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.


1 Answers

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.

like image 193
Sophie Alpert Avatar answered Sep 19 '22 23:09

Sophie Alpert