I’m going to do my best to explain(or walk through) what is happening. I’m also making two assumptions, in point 7 and point 10.
- App component mounts.
useEffectis called after the mounting.useEffectwill ‘save’ the initial state and thuscounterwill be 0 whenever refered to inside it.- The loop runs 3 times. Each iteration
setCountis called to update the count and the console log logs the counter which according to the ‘stored’ version is 0. So the number 0 is logged 3 times in the console. Because the state has changed (0 -> 1, 1 -> 2, 2 -> 3) React sets like a flag or something to tell itself to remember to re-render. - React has not re-rendered anything during the execution of
useEffectand instead waits till theuseEffectis done to re-render. - Once the
useEffectis done, React remembers that the state ofcounterhas changed during its execution, thus it will re-render the App. - The app re-renders and the
useCounteris called again. Note here that no parameters are passed to theuseCountercustom hook.
Asumption: I did not know this myself either, but I think the default parameter seems to be created again, or atleast in a way that makes React think that it is new. And thus because thearris seen as new, theuseEffecthook will run again. This is the only reason I can explain theuseEffectrunning a second time. - During the second run of
useEffect, thecounterwill have the value of 3. The console log will thus log the number 3 three times as expected. - After the
useEffecthas run a second time React has found that the counter changed during execution (3 -> 1, 1 -> 2, 2 -> 3) and thus the App will re-render causing the third ‘render’ log. - Asumption: because the internal state of the
useCounterhook did not change between this render and the previous from the point of view of the App, it does not execute code inside it and thus theuseEffectis not called a third time. So the first render of the app it will always run the hook code. The second one the App saw that the internal state of the hook changed itscounterfrom 0 to 3 and thus decides to re-run it, and the third time the App sees the internal state was 3 and is still 3 so it decides not to re-run it. That’s the best reason I can come up with for the hook to not run again. You can put a log inside the hook itself to see that it does not infact run a third time.
This is what I see happening, I hope this made it a little bit clearer.