React States & Asynchronous Callbacks

January 17, 2019

We all love the concept of the React state! You can trigger updates on data that are part of the scope of your component, and that'll trigger a re-render reflecting the new state.

Now there are 2 ways to initialize the state:

// #1
class App extends React.Component {
   constructor() {
     super();

     this.state = {
       count: 10,
       message: 'Hello'
     }
   }
}

// #2
class App extends React.Component {
   state = {
       count: 10,
       message: 'Hello'
   }

   render() {
      ...
   }
}

2 common ways to set the state:

// Wrong
this.state.comment = 'Hello';

// Correct
const newState = this.state;
newState.comment = 'Hello';
this.setState(newState);

// Better Way
this.setState({
   ...this.state,
   comment: 'Hello'
});

Using the setState asynchronous callback:

this.setState({
   ...this.state,
   comment: 'Hello'
}, () => {
   console.log("State updated", this.state);
});