useEffect hook
Maya Ifrim

Maya Ifrim

Mar 14, 2023

useEffect hook

useEffect is a hook in React that manages side-effects in functional React components.

Side effects refer to any action that affects something outside of the component, such as fetching data from an API, modifying the DOM, or setting up event listeners.

The useEffect hook takes two arguments: a function to perform the side effect, and an array of dependencies that determine when the effect should be triggered.

By default, useEffect runs after every render. However, you can control when the effect runs by specifying dependencies as an array in the second argument.

Below, example of how to use useEffect to fetch data from an API:


In this example, we pass an empty array as the second argument to ensure that the effect is only triggered once, when the component mounts.

If the dependencies are not provided correctly and you are setting a piece of local state when the state is updated, the default behavior of React is to re-render the component.

In the example above, without the dependencies array useEffect runs after every render causing an infinite loop and this effectively breaks the application. To ensure that the effect function is executed only once after the initial rendering of the component, it is recommended to use an empty dependencies array when updating state within your useEffect.

Async effects

useEffect can be used with async/await syntax to handle asynchronous operations. The async code can be wrapped in a function and call it inside the effect.

For example:


In this example, data is fetched asynchronously and data state variable is set using setData.

Cleaning up effects

Sometimes side effects need to be turned off. For instance, when have a countdown timer using the setInterval(), that interval will not stop unless the interval is cleared. In the example below, we create an interval that decrements the count by 1 every second, and return a cleanup function that clears the interval when the component unmounts or when the effect is re-run.


Maya Ifrim

Maya Ifrim

Passionate React developer with a love for crafting beautiful and user-friendly interfaces.

Leave a comment

Related Posts