How to use and implement useEffect()

Using useEffect is crucial for managing side effects in functional components in React. Here's a guide on how to use and implement useEffect, and when it's appropriate to do so:


When to Use useEffect:

  • Performing Side Effects: Use useEffect when you need to perform side effects like data fetching, subscriptions, or manually changing the DOM.

  • Cleaning Up After Component Unmount: Use useEffect for cleanup logic when the component is unmounted.

  • Managing Effect Dependencies: Use useEffect when you want to manage dependencies that should trigger the effect to run.

How to Use useEffect:

  • Import the Hook: Import the useEffect hook from React.
  • Define the Effect Function: Define a function that represents the side effect you want to perform.
  • Invoke useEffect with Effect Function and Dependencies: Call useEffect and provide the effect function as the first argument. Optionally, provide an array of dependencies as the second argument.

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

const DataFetchingComponent = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Function to fetch data
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    };

    // Call the fetch function
    fetchData();
  }, []); // Empty dependency array means this effect runs once

  return (
    <div>
      {loading ? 'Loading...' : <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  );
};

export default DataFetchingComponent;

In this example, useEffect is used to fetch data when the component mounts. The effect runs once due to the empty dependency array. The effect also sets up a cleanup function for any necessary cleanup operations when the component is unmounted.

Post a Comment

Previous Post Next Post