1

I have seen different variations of handling states in ReactJS tutorials.

I have seen the following:

class App extends Component {
    constructor () {
        super()
        this.state = {
            message: null,
        };
    }    

    componentDidMount() {
        fetch('/api/hello')
           .then(response => response.json())
           .then(message => this.setState({ message }));
    }
}

and

class App extends Component {
    state = {};

    hello = () => {
        fetch("/api/hello")
           .then(response => response.text())
           .then(message => this.setState({ message }));
    };
}

Both behave as expected, i.e. it was able to render the message from /api/hello. I am wondering the difference between the two where one is setting the state in the constructor and the other isn't.

Robin
  • 575
  • 2
  • 10
  • 26
  • Possible duplicate of [What is the difference between using constructor vs state = {} to declare state in react component?](https://stackoverflow.com/questions/45451141/what-is-the-difference-between-using-constructor-vs-state-to-declare-state) – Giorgi Moniava Oct 31 '18 at 15:12

1 Answers1

0

state is essentially a class field, so setting it in the field requires a this. prefix, whereas treating it like a class field, and not setting it in the constructor does not require this.. The key difference is that when put in the constructor, the state is set when the class is instantiated, whereas when it is outside the constructor it belongs to the class.

rileyjsumner
  • 523
  • 1
  • 8
  • 21