What will happen if I use setState() function in constructor of a Class in ReactJS or React Native?

What setState essentially does is to run a bunch of logic you probably don't need in the constructor.

When you go state = {foo : "bar"} you simply assign something to the javascript object state, like you would any other object. (That's all state is by the way, just a regular object local to every component).

When you use setState(), then apart from assigning to the object state react also rerenders the component and all it's children. Which you don't need in the constructor, since the component hasn't been rendered anyway.


Error Message would be Uncaught TypeError: Cannot read property 'VARIABLE_NAME' of null

Please see the following two jsfiddle snippets.

Case 1) Working solution jsfiddle

class Hello extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        name: 'world'
      } 
    }

  render() {
    return <div>{this.state.name} </div>
  }
}

ReactDOM.render(<Hello />, document.getElementById('container'));

Case 2) Not working solution

class Hello extends React.Component {
    constructor(props) {
      super(props);

      this.setState({
        name: 'hello'
      });
    }

  render() {
    return <div>{this.state.name} </div>
  }
}

ReactDOM.render(<Hello />, document.getElementById('container'));

Conclusion:

My rule of thumb, inside constructor uses this.state = {} directly, other places use this.setState({ });


Constructor: Constructor is Used to initialize the state.

State : Components that contain local state have a property called "this.state".

SetState: React components have a method available to them called setState Calling "this.setState" causes React to re-render your application and update the DOM.you can also track of prevstate in setState If you use setState in constructor you would get error like this:Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.