React useEffect Practical Guide


useEffect hook in different scenarios:

Fetching Data from an API:

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

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

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      setData(data);
    };

    fetchData();
  }, []);

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

In this example, the useEffect hook is used to fetch data from an API when the component mounts. The empty dependency array [] as the second argument ensures that the effect is only executed once. The fetched data is stored in the component’s state (data) using the useState hook.

Subscribing to a Real-Time Data Source:

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

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

  useEffect(() => {
    const subscription = realTimeService.subscribe((newData) => {
      setData(newData);
    });

    return () => {
      subscription.unsubscribe();
    };
  }, []);

  return <p>Real-time data: {data}</p>;
};

In this example, the useEffect hook is used to subscribe to a real-time data source when the component mounts. The returned cleanup function unsubscribes from the data source when the component unmounts. The empty dependency array ensures that the effect is only executed once.

Handling Component Updates:

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

const MyComponent = ({ value }) => {
  const [formattedValue, setFormattedValue] = useState('');

  useEffect(() => {
    setFormattedValue(formatValue(value));
  }, [value]);

  return <p>Formatted value: {formattedValue}</p>;
};

In this example, the useEffect hook is used to update the formatted value whenever the value prop changes. The effect is triggered whenever the value prop is updated, allowing the component to respond to changes and update the formattedValue state accordingly.

Cleaning Up Side Effects:

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

const MyComponent = () => {
  const [isVisible, setIsVisible] = useState(true);

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

    return () => {
      clearInterval(timer);
    };
  }, []);

  const toggleVisibility = () => {
    setIsVisible((prevIsVisible) => !prevIsVisible);
  };

  return (
    <div>
      <button onClick={toggleVisibility}>Toggle Visibility</button>
      {isVisible && <p>Visible content</p>}
    </div>
  );
};

In this example, the useEffect hook sets up an interval that logs a message every second. The returned cleanup function clears the interval when the component unmounts. This ensures that the interval is properly cleaned up and prevents memory leaks.

These examples showcase various scenarios where the useEffect hook can be used in React components. Remember that the second argument to useEffect (the dependency array) determines when the effect should be triggered. An empty dependency