Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda