I wrote a very small demo involving
useEffect() today. Actually, before that, I happened to be reading about
useEffect() in some article and caught myself confused. I had been always confident that I knew the finer details, but I just couldn’t tell one thing — will the effect run on the first render if the dependencies are listed exhaustively?
If you’re laughing at me, let me join as well — 🤣🤣🤣🤣.
But the point is, something this small was worrying me because I had forgotten and wasn’t sure. So, what do we do when we’re not sure? That’s right, create a working demo!
And so I created a demo and got to confirm two things: 1)
useEffect() provides a neat separation of concerns of sorts, as different variables can control different side-effects. 2) No matter which form of
useEffect() you use, it will always run at least once (the first render, that is).
Which begs the question: Is it possible at all to prevent the execution of a
useEffect() at the time of first render? Sadly, no. While you can add a conditional to make the effect return null or something, the function will always be invoked by React.
My advice: Don’t over-react to that! 😝😝