The Effects of useEffect

The Effects of useEffect

An introduction to the mysterious and popular useEffect Hook

The Why and What?

Have you ever wondered how to make side Effects occur when your component mounts, when it unmounts or when a variable/state/props change? If not, I suggest you tinker around with that idea and if Yes, then the answer to your prayers is useEffect

But hold up, hold up. What’s a side effect?

The Sneaky Side Effect

A side effect is anything that affects something outside the scope of the logic of your function. For example, when you’re making a network request, which involves your code communicating with the server, fetching data, logging the data, saving it in a state, all side effects which you didn’t mention in your function.

So now that you’ve understood , side effects let’s get to understand about a hook to aid you in creating them in a controlled fashion.

Syntax

useEffect(callback, [dependencies])
  1. The useEffect hook takes two arguments, a callback function to define a side effect.

  2. An optional dependency array which allows us to control when the side effect should be ran.

Let’s understand the different usages of useEffect now then :

The Infinite Runner : On Every Render

The most basic way of using useEffect is to pass a callback function to it like shown below

useEffect(()=>{
console.log(" I run on every render. ")
})

So, this block of code within the useEffect will run on every render, so every time a re-render occurs, you guessed it, the log runs.

So this basically means that every time the app mounts, unmounts, a variable changes, or the state gets updated, you now have the power to run your function thanks to useEffect. And this can be especially useful when you want to display the time at the tab title that changes every second, or in this scenario when the variable/state holding the value of time gets changed.

Okay, great news! But what if I do not want it to get updated on every state update? Is my code destined to run forever? Is there no one strong enough to stop him?

Of course, there is, like the kryptonite to superman we have our second argument in useEffect called The Dependency Array.

The Runner's Leash: The Dependency Array

So any value in the dependency array will be compared against its previous render’s values and the side effect will be caused only when the values of those dependents change. So this means, if you want it to run only on mount then you would provide it with

Come on! You can do it.

Hint: It rhymes with nothingness.

Nothing aka Emptiness.

So if you provide the useEffect hook with an empty array as a dependency, it only runs once on the component mount.

useEffect(()=>{

console.log("I run only on Mount")

},[])

Having the control of when the useEffect runs are nice since we get to decide when the side Effect should be triggered.

Being in control:On Every State/ Props Update

So now that we know how to run a side effect on mount and on every render, let’s get some more control over it.

useEffect(()=>{
console.log("I run only when the state or props gets updated")
}, [state/props]

In this case, the Side effect will run only when the state value or props value provided in the dependency array gets updated, and so this way we minimise unnecessary side effects.

Now that we have made up all these side effects, who’s gonna clean them up? 👀

The Cleaner : Side Effect Cleanup

So far we know how and when to run a side effect and for the sake of not let it hog your app’s performance, we need to clean the colorful mess we make too.

Basically, whatever you’re doing in the side effect , you’re supposed to do the opposite in the cleanup function and return that.

useEffect(()=> {
//Side Effect
console.log("I made a mess!")
return () => {
//Side Effect Cleanup
console.log("I cleaned it up")
}
},[props,state]);

Every time a new side effect is run, the cleanup function works first and cleans up the previous side effect, giving your new side effect a fresh start.

Reinforcing what we learnt

Uff! , too much technical stuff right? You sure you got it all? Let’s make sure you did.

  1. Use Effect is like a building security guard, who can roam and guard
  2. All the time, every time he notices a change ( On Every Render )
  3. Once a night ( Once on mount/unmount )
  4. Only when he hears certain sounds or sees suspicious activities ( On dependent value updates )

If you could relate to these sentences with what we read, then kudos! If not, don’t fret give it another go, maybe you’re brain will register only in the second render :P

So that’s it folks, hope you feel a little less intimidated by UseEffect now.

And if you’re wondering where’s the relatable example for cleanups, that’s where you come in.

Let me know how you run that side effect on your brain. See you in the next one!