Doubt regarding the lesson : How to deal with side effects #27805
-
In "the clean-up function" section of Using effects save the day in the above article it is written that : "..... When the component is unmounted, setInterval is not stopped, it keeps incrementing...." I think it should be ".....When the component is updated, setInterval is not stopped, it keeps incrementing......" As the component is not unmounted it is being updated when the Clock component re-renders with a different counter state. Is it so or I'm missing something? A screenshot of the concerned part of the lesson is attached for reference |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The lesson verbiage is correct. The example has the interval set in a Since the empty dependency array means the effect will never run again after it runs on mount, then the only time the cleanup function runs will be when you unmount the component. If the dependency array contained variables, then the effect would rerun every time once of those variables changes value, in which case the cleanup function will run before each of those effect reruns. But otherwise, effects do not rerun just because a component updates in some way. It's specifically only if anything in the dependency array changes. And since the example has nothing, it will never re-run. You'll note in the 3rd paragraph, it says this:
Hope that clears things up! |
Beta Was this translation helpful? Give feedback.
The lesson verbiage is correct. The example has the interval set in a
useEffect
with an empty dependency array, meaning the effect callback runs once on component mount, then never again. The cleanup function runs before every re-run of the effect, and once upon component unmount.Since the empty dependency array means the effect will never run again after it runs on mount, then the only time the cleanup function runs will be when you unmount the component.
If the dependency array contained variables, then the effect would rerun every time once of those variables changes value, in which case the cleanup function will run before each of those effect reruns.
But otherwise, effects do not re…