Lazy learning: React useEffect hook

Before reading this, you should know the basics of states and props, and that every time they change, the whole component re-renders.

To start useEffect and other react hooks, one must know what the lifecycle of components in react is. Here’s a diagram that tells you straight:

A diagram that shows the phases of the react life cycle: Mount, Update, and Unmount

It’s a simple diagram but really shows what it is in a nutshell. What makes the useEffect hook great is that it can be used in all phases of the lifecycle. So let’s get right into it.

on every update

useEffect can be used to run code on each update or re-render of the component it’s used in.

useEffect(() => {
console.log("I run every time.");

It will always call the function that’s passed into it whenever the component is updated or re-rendered. Make sure not to set a state inside, since that will cause an infinite loop.

on mount

useEffect can also be used to run code only once in the whole life-cycle of that component. Which allows us to do things such as fetching data from an API and set it as a state, we don’t have to worry about the whole infinite looping because it will always run once.

useEffect(() => {
console.log('I run only once!');
}, []);

Notice we pass a second argument which is an empty array. We do this to tell useEffect that we don’t depend on anything for it to call the function passed. This will get more clearer later on.

on when dependencies change

we can then pass in “dependencies” into the second array to tell useEffect that we only want to run this code when one or more dependencies change. dependencies are typically props or states.

const [ color, setColor ] = useState('red');

useEffect(() => {
console.log('I run only when color changes!');
}, [color]);

on unmount

we usually do this whenever we want to “clean up” at the end. A very easy example of this is removing an interval call set with setInterval or sending a post request to a server.

useEffect(() => {
console.log('I run only once!');
return () => {
console.log('The component was unmounted!');
}, []);

Notice that we now return another function inside our first argument. This is how we tell useEffect what to call when the component is unmounted.

the syntax

The first argument is the callback function and the second is an array of “dependencies

// Parameters.
useEffect(<function>, <array of dependencies || optional>);

Alright, now you know how to masterfully use useEffect! In most cases though, you’ll only be using it to fetch data on mount.

I make simple yet exhaustive content on web development.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store