techStackGuru

React useEffect Hook


In React, the useEffect hook allows developers to perform side effects on functional components. A common use for it is to retrieve data, subscribe to events, and manipulate the DOM.

React 16.8 introduced the React Hooks API, which includes the useEffect hook. The hook allows functional components to have similar lifecycle methods to class components. The useEffect property allows you to specify what should happen after a component renders, updates, or unmounts.

In general, useEffect looks like this:

useEffect(() => {
    // Side effect code goes here
    return () => {
      // Cleanup code goes here (optional)
    };
  }, [dependencies]); 

UseEffect takes a function as its first argument, which represents the side effect you wish to perform. Every time the component is rendered, this function will be executed.

In the second argument, you can specify an array of dependencies. Each render will re-execute the effect function if one or more dependency changes. After the initial render, the effect will only run once if the dependencies array is empty.

No dependency passed:

useEffect(() => {
    //Runs on every render
  }); 

An empty array:

useEffect(() => {
    //Runs only on the first render
  }, []); 

Props or state values:

useEffect(() => {
    //Runs on the first render
    //Whenever the value of any dependency changes
  }, [prop, state]); 

Example 1: Fetching data using useEffect

import React, { useEffect, useState } from 'react';

  const MyComponent = () => {
    const [data, setData] = useState([]);
  
    useEffect(() => {
      const fetchData = async () => {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      };
  
      fetchData();
    }, []);
  
    return (
      <div>
        {data.map(item => (
          <p key={item.id}>{item.name}</p>
        ))}
      </div>
    );
  };
  

The purpose of this example is to use useEffect to retrieve data from an API and update the state of the component using the result. The effect runs only once, after initial rendering, due to the empty dependencies array.

Example 2: Cleanup

import React, { useEffect, useState } from 'react';

  const MyComponent = () => {
    const [count, setCount] = useState(0);
  
    useEffect(() => {
      const timer = setInterval(() => {
        setCount(prevCount => prevCount + 1);
      }, 1000);
  
      return () => {
        clearInterval(timer);
      };
    }, []);
  
    return <div>Count: {count}</div>;
  };
  

The following example shows how to create an interval that increments a count every second using useEffect. By returning a cleanup function, useEffect prevents memory leaks caused by unmounting components.