Adding Side Effects with useEffect()

Learn how to add side-effects in function components while avoiding code duplication present in lifecycle methods of class components.

useEffect() vs. lifecycle methods

The name of the useEffect() Hook derives from its intended usage: for side effects. In this case, we mean loading data via an API, registering global events, or manipulating DOM elements. The useEffect() Hook includes functionality that was previously found in the componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.

If you’re wondering whether all these lifecycle methods have now been replaced and been combined into a single Hook, you’re correct. Instead of using three methods, you only need to use a single Hook, which takes effect in similar places where the class component methods were previously used. The trick is to use particular function parameters and return values that are intended for the useEffect() Hook.

Replacing componentDidMount() lifecycle method

In order to use the useEffect() Hook, we pass the useEffect() function another function as its first parameter. This function, which we will call the effect function for now, is invoked after each rendering of the component and “replaces” the componentDidMount() part of class components.

Since this effect function is called after each render of the component, it is also called after the first render. This equates to the working of componentDidMount() lifecycle method.

Replacing componentWillUnmount() lifecycle method

Moreover, the effect function can optionally return another function. Let’s call this function a Cleanup function. This function is invoked during the unmounting of the component, which roughly equates to the componentWillUnmount() class component method.

Note: Be careful. While this sounds similar, the useEffect() Hook works slightly differently than class components’ lifecycle methods. Our cleanup function is not only called during the unmounting of the component but also before each new execution of the effect function.

Dependency array

The second parameter of the useEffect() Hook is the dependency array. The values of this array indicate the values upon which the execution of the effect function depends on. If a dependency array is passed, the Hook is only invoked initially, and then only when at least one of the values in the dependency array has changed.

If we explicitly try to replicate behavior previously covered by componentDidMount(), we can pass an empty array as our second parameter. React then only executes the effect function on the initial render and only calls a cleanup function again during unmount.

This probably sounds very complex and theoretical now, especially if you are new to Hooks and do not quite understand how they work. Let’s look at an example to clear things up a little:

Get hands-on with 1200+ tech skills courses.