useEffect()

In React, useEffect is a Hook that allows you to perform side effects in your functional components. Side effects can include, for example, data fetching, manual DOM manipulations, and more.

import React, { useEffect } from 'react';
 
const App = () => {
  useEffect(() => {
    // Effect code here
    console.log('Component mounted or updated!');
     
    // Cleanup function (optional)
    return () => {
      console.log('Cleanup code here');
    };
  }, []); // Dependency array, empty means the effect runs once after the initial render
 
  // Component JSX
  return (
    <div>
      {/* Your component content */}
      <p>Content</p>
    </div>
  );
}
export default App;

There are various ways to use useEffect(), and the distinction lies in what is provided as the second parameter at the end of the Hook call:

useEffect(() => {
  // The code here runs on every render
}, []); 
// An empty dependency array means this effect runs once and when the component mounts(render).
//The subsequent renders will not trigger it again.
useEffect(() => {
  //The code here runs on every render on the absence of the second parameter.
});
useEffect(() => {
  //The code here runs on the first render and any time any value changes in given variable. 
  //The variable can also be prop or state.
}, [someVariable]);

The clean-up function is useful for tasks like clearing intervals when the component is unmounted or when specific dependencies change. Here is an example:

useEffect(() => {
  // Code here runs on every render

  // Clean-up function
  return () => {
    // Code to run when the component unmounts or when the dependency changes
  };
});

Here’s an example of how to use the React Hook useEffect to fetch data from an API:

import React, { useState, useEffect } from 'react';
import "./style.css";

export default function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const url = "https://my.api.mockaroo.com/co2.json?key=8eb9e6f0";
    fetch(url).then(response=> {
       // It's beneficial to check for errors here as not all errors are caught by the catch block.
       if (!response.ok) {
            throw new Error(response.statusText);
        }
        return response.json();
    }).then(response=> { 
          // Do something with the data
          setData(response); 
   }).catch(error => {
    console.error("There was a problem with the Fetch operation");  
});
}, [])// Empty dependency array means the effect runs once after the initial render

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.Year}>{item.Year}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

Here’s another example of creating a timer by using useEffect().

import React, { useState, useEffect } from 'react';
import "./style.css";

export default function App() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);

    // Cleanup: Clear the interval when the component unmounts
    return () => clearInterval(intervalId);
  }, []); // Empty dependency array means the effect runs once 

  return (
    <div>
      <p>Seconds elapsed: {seconds}</p>
    </div>
  );
}

Read more:

https://react.dev/reference/react/useEffect

https://www.w3schools.com/react/react_useeffect.asp

Scroll to Top