How and When to Use useEffect Hook in React

The useEffect hook in React is a popular hook that you usually learn about early on in your React learning experience. However, there can be some confusion about when it is appropriate to utilize it and when you should use something else instead.

The useEffect hook is useful because it can perform a function before your component renders. There are many benefits to doing that, but you need to make sure you don’t abuse it or else you can risk having some funky things happen in our code.

How to use useEffect

First, import useEffect from react like so: import {useEffect} from React

Importing useEffect into code editor

Second, place your useEffect statement at the top of your main function. You don’t want to place your useEffect randomly in your function as that can cause some unexpected issues. Plus, it’s just plain bad practice.

Third, place your logic inside the callback function. This is the functionality that will run when the useEffect is triggered.

Implementing useEffect into code editor

Fourth, input your dependency array. The dependency array will most often be an empty array. An empty array means that the useEffect hook will run once on the page renders.

Placing any other variables or props in that dependency array will trigger the useEffect hook to run every time values change in the respective variable or prop.

Failing to correctly setup your dependency array can cause your app to run in an infinite loop and crash your app.

When to use useEffect

You should only use the useEffect hook when dealing with something outside of React like fetching data from an api or working with an external tool. It is described in the React docs as an “escape hatch”, therefore useEffect should be limited to things that can’t be performed with the normal React framework.

“If you’re not trying to synchronize with some external system, you probably don’t need an Effect.”

One good example would be fetching data from an api that you need to display in your component. The api is something outside of your React framework and there really isn’t a better way to do that.

One bad example would be running the calculation “x + y” so you can render the result in your component. You don’t need to break out of the React framework to make that sort of calculation, so don’t implement a useEffect hook for that.

It’s a good idea to limit your useEffect hook implementations as much as possible so as to avoid any potential hiccups in your React app.