useEffect

Learn how to add side effects in function components and the rules to follow while using the useEffect Hook.

This Hook is intended for imperative side effects such as API requests, timers, or global event listeners. Normally, these side effects should be avoided in function components, since they can lead to unexpected behavior or bugs that might be hard to solve.

The useEffect() Hook combats this problem and allows for a safe mechanism to use side effects within function components.

We call useEffect() in the following way:

useEffect(effectFunction, dependenciesArray);

The Hook expects a function as its first parameter and a dependency array as its second. The function is called after the component has rendered. If we have passed an optional dependency array to this Hook, the function we pass will only be executed if at least one of the values in the dependency array has changed. If an empty dependency array is passed, the function will only be run on the first render of the component, similar to the componentDidMount() lifecycle method.

Cleaning up side effects

Sometimes side effects leave “traces” that have to be cleaned up once a component is no longer in use. If, for example, you had intervals that you had started with setInterval(), these should be stopped with clearTimeOut() once the component has been removed. If left untreated, these side effects can lead to actual problems or even memory leaks.

Globally registered event listeners such as resize or orientationchange, which have been added to the window object with addEventListener() should also be removed once the component unmounts by using removeEventListener(). This method will prevent further execution if the component itself is no longer part of the component tree.

To make this cleanup a bit more systematic and easier, we can return a cleanup function from the effect function. If an effect function returns a cleanup function, it is called before each call of the effect function, with the exception of the very first call:

Get hands-on with 1400+ tech skills courses.