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

133
Visualizações
How the Setstate work behind the scenes in React
import React,{Component} from "react";
class Message extends Component{
constructor()
{
    super()
    this.state={
        message:0
    }
  
}
changemessage()
{
    this.setState(
        prevState=>({
            message:prevState.message+1
        }
    ),
    ()=>
        {
           console.log( 'callback value',this.state.message)

        }
    )
   
}
sample()
{
    this.setState(
        prevState=>({
            message:this.state.message+1
        }
    ),
        ()=>
        {
           console.log( 'callback value',this.state.message)

        }
    )
   
}

convert()
{
    this.changemessage()
    this.sample()
    this.changemessage()
    this.sample()
    this.changemessage()
    this.sample()
    this.changemessage()
    this.sample()
    this.changemessage()

}
render()
{
    return(
        <div>
        <h1 >{this.state.message}</h1>
        <button onClick={()=>{this.convert()}}>Subscribe</button>
        </div>
    )
}
}

To understand the SetState i used two function with prev state and this.state.I expect 9 as answer .but i get 2 as a answer printed in console for 9 times.if i use Prev State in both function instead of this.state.message in sample function i got 9 as a answer.i want to know what happening in the background if i use like this.

about 4 years ago · Juan Pablo Isaza
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