Home > OS >  Why don't React component functions break/terminate when state is changed?
Why don't React component functions break/terminate when state is changed?

Time:04-27

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().

CodePudding user response:

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.

  • Related