I'd like to clarify my understanding of what's happening here. Any detail to improve my current understanding'd be appreciated.
function Timer() {
let [time, setTime] = useState(5);
useEffect(() => {
let timer = setInterval(() => {
setTime(time - 1);
}, 1000)
return () => clearInterval(timer);
}, );
return <div>{time}</div>
}
export default Timer
https://codesandbox.io/s/cranky-chaplygin-g1r0p
time
is being initialised to5
.useEffect
is read. Its callback must be made ready to fire later.- The
div
is rendered. useEffect
's callback is executed.setInterval
's callback gets ready to fire. SurelyuseEffect
'sreturn
statement doesn't fire here, because if it did it would cancel the timer (and the timer does work).- After, roughly, 1 second,
setInterval
's callback fires changing the state oftime
(to 4). - Now that a piece of state has changed, the function is re-executed.
time
, a new variable, is initialised to the new time state. - A new
useEffect
is read, it's callback made ready to fire later. (This happens because there is no 2nd argument ofuseEffect()
). - The component function's
return
statement is executed. This effectively re-renders thediv
. - At some point, the previous
useEffect
'sreturn
statement executes (which disables thetimer
in that previoususeEffect
). I'm not sure when this occurs. - The 'new'
useEffect
's callback is executed.
from When does the useEffect's callback's return statement execute?
No comments:
Post a Comment