r/learnjavascript • u/kkokane • Sep 04 '21
I created an Illustrated version of the useEffect hook
16
u/Infase123 Sep 04 '21
Correct me if I am wrong, but when there are dependencies in the array, the useeffect hook always runs the first time, after that it only runs if any dependencies change.
2
u/kkokane Sep 05 '21
Yes, you are right. One way that I look at it is that the dependency array did not exist before the first render. So having it in the first render is a "change" from not having it before that. I hope I'm making sense. :)
4
u/Riley-96 Sep 04 '21
This is correct, from react docs https://reactjs.org/docs/hooks-effect.html
Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update.
6
3
u/Aer0za Sep 05 '21
Es lint will complain about that empty dependency array though. So annoying
1
u/kkokane Sep 05 '21
Well, If your use case is to pass empty dependency array then maybe you need to check whether you need useEffect in the first place or not?
1
4
u/diimitra Sep 05 '21
Decouple ?
Side effects ?
I swear sometimes I try to go and read doc but feel every word is so hard to understand...
2
u/kkokane Sep 05 '21
Will surely create a #sketchnote explaining terms like these. Please post more of them so that I can cover as many as I can in a single note :)
3
u/ovidius72 Sep 05 '21
Anyway, those are terms not strictly related to react. I think anyone in the software developer field should know what they mean.
2
8
Sep 04 '21
Jesus, am I drunk or is this the clearest explanation I've ever seen? both?
5
Sep 05 '21
It’s clear if you already know it and just need a refresher.
2
u/Dimitar_Petrov Sep 05 '21
I have never heard of it and seems pretty clear to me. Nearly zero front-end experience. It is super neat!
1
Sep 05 '21
Can useEffect be called inside an array?
Can dep be a deeply linked object?
Can the order of the elements in dep be changed dynamically?
Can dep be an array of arrays?
4
Sep 04 '21
How did you do this sketch note ?
10
u/agustin_edwards Sep 04 '21
1
u/petepete Sep 05 '21
My favourite diagramming tool ever. Completely switched to it for work stuff, recommend it to anyone who asks. It's the only PWA I have ever 'installed'.
4
2
2
2
u/Izero_devI Sep 05 '21
Keep in mind that 'effect will run when dependency changes' part can be misleading.
A better version would be ' Effect will run after a render if the dependency changed'. I saw some people put useRef variables in the dep array, but that variable doesn't trigger render after it is changed, which means useEffect dependency comparison cannot even happen when there is no render.
2
Sep 05 '21
I think more clear if you put as it’ll run on first render + if dep changes for final one.
1
26
u/ARFiest1 Sep 04 '21
Where is part 2 ?