Everything you need to know about React’s useEffect

useEffect is a Hook in React that is used to handle side effects in functional components, such as fetching data, subscribing to events, and updating the DOM in response to a component’s props or state.

useEffect takes two arguments: a callback function and an array of dependencies. The callback function is called after the component renders and it should contain the side effect logic. The array of dependencies is used to determine when to re-run the effect.

Here is an example of using useEffect to fetch data in a component. If you’re familiar with the class-based components, this is equivalent to componentDidMount():

import { useEffect, useState } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);

  // Since we're passing in empty [] array, this is run only once. 
// Replace with a real API to test the code.

  useEffect(() => {
    fetch('https://my-api.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return <div>{data.map(item => item.name)}</div>;
}


In this example, the useEffect hook is used to fetch data from an API when the component is rendered. The empty array [] passed as a second argument to useEffect means that the effect will only run once, when the component is first rendered.

You can also add variables to the dependency array, which will make the effect re-run whenever the variables change. If you’re familiar with class-based components, this is equivalent to componentDidUpdate()

import { useEffect, useState } from 'react';

function MyComponent({ id }) {
  const [data, setData] = useState([]);

  // This is executed whenever the id in the dependency array changes. 
// Replace with a real API to test the code.

  useEffect(() => {
    fetch(`https://my-api.com/data/${id}`)
      .then(response => response.json())
      .then(data => setData(data));
  }, [id]);

  return <div>{data.name}</div>;
}

In this example, the component receives an id prop and the useEffect hook is used to fetch data based on the id prop. The id prop is added to the dependency array, so the effect will re-run every time the id prop changes.

You can also return a function from the callback function which will act as a cleanup function, it will be called before the component is unmounted or before the effect is re-run.

The below example is equivalent to class-based components’ componentWillUnmount() method:

import { useEffect, useState } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    const intervalId = setInterval(() => {
      console.log('Hello World');
    }, 1000);

    // Returning a function from the useEffect

    return () => clearInterval(intervalId);
  }, []);

  return <div>Check the console</div>;
}


In this example, the callback function sets an interval that logs “Hello World” to the console every second. And the cleanup function is used to clear the interval when the component is unmount or before the effect is re-run.

useEffect is a powerful tool that allows you to synchronize your component with an external system and manage side effects in a functional component. It allows you to fetch data, subscribe to events, and update the DOM in response to changes in props or state. However, it’s important to consider performance and not overuse the useEffect hook, as it can lead to unnecessary re-renders and slow down the performance of the application.

Leave a Reply

Your email address will not be published. Required fields are marked *