Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda