Best Practices For Resetting an ES6 React Component’s State(?)

Justin Tulk
2 min readOct 4, 2016

--

Update: Thoughts on whether or not this is an anti-pattern.

Say you have a component that contains a form with ‘Cancel’ and ‘Submit’ buttons. Updating any field in the form updates the `state` of the form, clicking ‘Cancel’ should reset the form to the initial state, and ‘Submit’ will submit (obviously).

It’ll look something like this using ES6 Class syntax:

import React, { Component } from 'react'class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
}
resetForm = () => {
// what goes here?
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val }) render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}

What’s the best way to reset the form on a ‘Cancel’ event? I’m currently doing it this way:

import React, { Component } from 'react'class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state

}
resetForm = () => {
this.setState(this.baseState)
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val }) render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}

It seems a lot easier and more reliable than messing around with `key` property value resetting. Anyone have a best practice for this?

Note: Kenneth Jiang notes in the comments that if you add additional properties to this.state after initializing the component, they will not be removed when doing this.setState(this.baseState). Those additional properties would need to be reset directly using something like this.setState({ ...this.baseState, otherSetProp: [whatever the reset value should be] })

--

--

Justin Tulk

Staff Software Engineer. Making computers do stuff since 2011.