My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

set initial state in react

ananth subbu's photo
ananth subbu
·Jan 4, 2018

today i was working on react form. usually i will reset the form in hard way (resetting every form value like this this.setState({data: '', value: [] })).

then came across a easy & best way in medium.thought of sharing with you all.

reference: medium.com/@justintulk/best-practices-for-r..

constructor(props){
    super(props)
    this.state = {
      inputVal: '',
      value: []
    }
    // preserve the initial state in a new object
    this.baseState = this.state 
  }
 resetForm = () => {
    this.setState(this.baseState)
  }