Search code examples
javascriptreactjsonchangesetstate

React - onChange event / setState


I tried to make a filter items functionality and I encountered the following code:

handleChange = e => this.setState({ [e.target.data.inputType]: e.target.value }, this.filterItems);

What is the purpose of the second argument filterItems when I use setState?


Solution

  • Think ofsetState as an asynchronous operation, if you need to do something after the state changes you should put it in the second parameter callback.

    In this example the code inside the condition may not be reached:

    // Assuming isReady initial value is false.
    this.setState({
     isReady: true
    });
    
    //At this moment this.state.isReady is probably still falsy.
    if (this.state.isReady) { ... }
    

    To be sure, you need to pass the code in the (After state) callback. With this, you guarantee your code will only be executed once the new state takes effect.

    // Assuming isReady initial value is false.
    this.setState({
     isReady: true
    }, () => {
      // React calls this function when the updates are applied.
      // Which means we are sure isReady have the new value.
      if (this.state.isReady) { ... }
    });
    

    Check the docs for more pieces of information:

    Think of setState() as a request rather than an immediate command to update the component.

    The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

    https://reactjs.org/docs/react-component.html#setstate