In this article, we will explore useEffect() hook and how it works without a dependency array.

useEffect without a dependency array

We use the useEffect() hook to run side effects when the component mounts, renders, re-renders, or unmounts.

Dependency array affects when the useEffect() hook runs. Passing an empty dependency array means that the effect runs once – only when the component mounts. useEffect() with multiple dependencies runs when any of the state dependencies change.

If the useEffect does not have a dependency array, it runs on mount and every time the component re-renders.

Let’s look at an example:

In some cases, it’s inefficient to run a side-effect when component mounts and every time it re-renders. Still, there are a number of use cases that justify having useEffect without a dependency array.

For example, if you need to adjust to external changes to DOM content or state values.

Do you really need useEffect without a dependency array?

If you want to run a useEffect() without a dependency array, chances are you don’t need useEffect() at all. It’s more readable to write directly in the function.

Function component itself runs on mount and every time component re-renders.

Adding side-effects in the render function (body of the functional component) achieves the same as using useEffect() without a dependency array. This side-effect will run every time component renders and re-renders.

Let’s look at this example once again:

If you un-comment the call to console.log() in the functional component, it will work the same as useEffect() without dependencies.

This approach is more readable than using useEffect() without the dependency array.

However, there is a small difference between useEffect() and performing a side effect directly in the function. If your side-effects deal with synchronization, you might need useEffect() anyway, because side-effect always performs after the component is rendered.

If you look at the console, you’ll see which console.log() executes first. Call in the function body runs first, followed by useEffect().