...

/

Adding Side Effects with useEffect()

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

...