'logic at initialization of the state/constructor vs ComponentDidMount in React

I was going through my code and realized I sometimes assign a logic when declaring the state and other times at ComponentDidMount.

  constructor(props) {
    super(props);
    this.state = {
      api: localStorage.getItem("api") ? true  : false,
    };

other times I do this instead

  constructor(props) {
    super(props);
    this.state = {
      api: null,
    };

componentDidMount() {
this.setState({api: localStorage.getItem("api") ? true  : false})
}

They seem to behave the same way but I am sure there are a few subtle differences. which one is the most correct?



Solution 1:[1]

As the execution flow of statements in react, i personally use constructors for stubs or initialising functions/variables/params or setting the functions ready once render is executed. The reasons react docs asks you to initialise state in constructor itself is to set a pre-defined values in it, so as to when componentWillMount(deprecated) would be executed it can compare with props.

Here your localstorage get item works because these are window or browser defined statement or functions of JS, if you write them outside the class or function they would still work. They don't have any dependancy on how the function or class will behave.

ComponentDidMount should be the pattern to set the values or do something funky in your component. As its executed after render it has various useful capabilities to do, like async calls or setState or set ref , Ex: the way you did setState in didMount is to set the values for component .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddharth Pachori