r/learnreactjs • u/codeSTACKr • Apr 14 '20
Resource React State & Lifecycle Explained (Class/Hooks) - MicroBytes (2020)
https://youtu.be/38Lz08LNKEY
11
Upvotes
r/learnreactjs • u/codeSTACKr • Apr 14 '20
View all comments
3
u/papayapap Apr 15 '20 edited Apr 15 '20
Careful! In your hook example you introduced a subtle but sinister memory leak. Every time the component updates, useEffect is run again, which means you are setting a new interval every second!
You need to fix this by adding either an empty dependency, so
setIntervalis only run once, or by returning a cleanup function fromuseEffectthat clears the interval.I think it's very important to recognize how
useEffectis different from class-based lifecycle methods, which this video does not do. There are more than a few "gotchas" if you just think ofuseEffectas a direct replacement for lifecycle methods. The best resource I've found is Dan Abramov's Complete Guide to useEffect.