Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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 .

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!