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

133
Views
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 answers
Answer question

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 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!