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

134
Visualizações
Why don't React component functions break/terminate when state is changed?
function App() {
  const [buttonClick, setButtonClick] = useState('No')
 
  async function handleClick(){
    setButtonClick('Yes')
    const sleep = (ms) ={return new Promise(resolve => setTimeout(resolve, ms))}
    await sleep(2000)
    console.log('this ran after state was changed')
  }
  
  return(
    <>
    <button onclick={handleClick}>Click me</>
    {buttonClick}
    </>
)
}

How come if I click the button, which sets the state of buttonClick, does it not break out of the function? It still sleeps for 2 seconds then logs my message in the console.

My thinking is that since it causes a component re-render, it would lead me to believe that the function App is returning and would break out of the handleClick function.

My thoughts on why this might be is that it might be when React is compiled it is just storing the value of the return somewhere else, and not actually returning the broader function App().

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This has more to do with how Javascript works rather than React, I'll do my best to explain:

  1. When you click the button your handleClick function is invoked.
  2. handleClick is now on the call stack and will not terminate until either a value is returned or an error is thrown.
  3. The first instruction in handleClick is to update the state, however, updating the state will not terminate the invokation of handleClick and even if the component were to unmount before it had a chance to finish, any call to setButtonClick on an unmounted component would result in what is known as a memory leak.
  4. Furthermore the setTimeout and async nature of this function will end up in various parts of the event loop, but that has little to do with the original question.

You can learn more about the nature of Javascript functions here.

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