DEV Community

AndrewCabana
AndrewCabana

Posted on

What is the UseEffect Hook and How to use it properly

In React, the useEffect hook has become a powerful tool that allows developers to perform side effects in functional components. useEffect is usefull in many scenarios whether you need to make a call to an API, subscribe to events, or clean up resources, useEffect provides a clean and concise way to handle these events. this post is aimed to explain what the useEffect hook is and how to use it effectively in your React apps.

Understanding useEffect:
The useEffect hook is a built-in function in React that allows you to perform side effects after rendering a component. Side effects include things like data fetching, subscriptions, or manually changing the DOM. useEffect is called after every render by default, but you can control when useEffect is called using dependencies.

Using useEffect:
To start using the useEffect hook, you first need to import it from the 'react' library:

Image description

The basic syntax of the useEffect hook looks like this:

Image description

The first argument to useEffect is the function that will be executed as a side effect. The optional second argument, 'dependencies,' is an array of values. If any of the values in the dependency array change, the effect will re-run. If you want the effect to run only once, pass an empty dependency array.

Example 1: Fetching data with useEffect

Image description

In this example, we use the useEffect hook to fetch data from an API. The effect is triggered only once when the component mounts (empty dependency array). It sets the fetched data to the 'data' state using the 'setData' function.

Example 2: Subscribing to events with useEffect

Image description

In this example, the useEffect hook is used to subscribe to the scroll event. The effect runs once when the component mounts, adds an event listener for scroll events, and removes it when the component unmounts (cleanup code).

Conclusion:
The useEffect hook is a fundamental tool in React for handling side effects. By understanding this hook and using the provided examples, you can leverage this hooks fuctionality to fetch data, subscribe to events, and perform other necessary operations in your functional components. Remember to use the dependency array wisely to control when the useEffect hook should run. With useEffect, you can write cleaner, more concise code in your React applications.

Top comments (0)