How to Use the React useEffect Hook

09/27/2021

Contents

In this article, you will learn how to use the React useEffect hook.

Using the useEffect hook

The useEffect hook is one of the most commonly used hooks in React. It allows you to execute side effects in function components, such as fetching data, subscribing to events, or updating the DOM.

Here’s how to use the useEffect hook:

Import the useEffect hook from the React package:

import React, { useEffect } from 'react';

Declare a function component and define the useEffect hook inside it. The hook takes two arguments: a callback function and an array of dependencies.

function MyComponent() {
  useEffect(() => {
    // Side effect code goes here
  }, [dependencies]);
  return (
    // Component JSX goes here
  );
}

The first argument to useEffect is a function that will be executed after the component has been rendered. This function is known as the “effect function”. You can use it to perform any side effects you need, such as fetching data from an API:

function MyComponent() {
  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  }, []);
  return (
    // Component JSX goes here
  );
}

In this example, we’re fetching data from an API using the fetch function. We’re passing an empty array as the second argument to useEffect, which means that the effect function will only be executed once, when the component is mounted.

The second argument to useEffect is an array of dependencies. This argument is optional, but it’s important to understand how it works. If you provide an array of dependencies, the effect function will only be executed if one of the dependencies has changed since the last render:

function MyComponent(props) {
  const { id } = props;
  useEffect(() => {
    fetch(`https://api.example.com/data/${id}`)
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  }, [id]);
  return (
    // Component JSX goes here
  );
}

In this example, we’re fetching data from an API based on the id prop. We’re passing [id] as the second argument to useEffect, which means that the effect function will be executed whenever the id prop changes.

If you don’t provide a second argument to useEffect, the effect function will be executed after every render:

function MyComponent() {
  useEffect(() => {
    console.log('Component rendered');
  });
  return (
    // Component JSX goes here
  );
}

In this example, we’re logging a message to the console after every render. We’re not passing a second argument to useEffect, which means that the effect function will be executed after every render.