React useEffect Hook

  • useEffect is a React hook that enables performing side effects in functional components.
  • It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class components.

Purpose

  • Handles asynchronous operations, data fetching, subscriptions, or any side effects in functional components.
  • Ensures that side effects do not cause performance issues or memory leaks.

Syntax

  • Import useEffect from the 'react' library.
  • Pass a function as the first argument, which will contain the code for the side effect.
  • Optionally, provide a dependency array as the second argument to control when the effect runs.
import React, { useEffect } from 'react';

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

Runs on every render

useEffect runs after every render without any specific dependencies.

import React, { useEffect } from 'react';

const EveryRenderExample = () => {
  useEffect(() => {
    // Runs after every render
    console.log('Effect ran on every render!');
  });

  return (
    <div>
      <p>Every Render Example</p>
    </div>
  );
};

export default EveryRenderExample;

Runs on first render

useEffect runs only on the first render with an empty dependency array.

import React, { useEffect } from 'react';

const FirstRenderExample = () => {
  useEffect(() => {
    // Runs only on the first render
    console.log('Effect ran on first render!');
  }, []);

  return (
    <div>
      <p>First Render Example</p>
    </div>
  );
};

export default FirstRenderExample;

Runs when data changes

useEffect runs when specific props or state values change.

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

const DataChangeExample = ({ propValue }) => {
  const [stateValue, setStateValue] = useState('');

  useEffect(() => {
    // Runs when propValue or stateValue changes
    console.log('Effect ran on prop or state change!');
  }, [propValue, stateValue]);

  return (
    <div>
      <p>Data Change Example</p>
    </div>
  );
};

export default DataChangeExample;

Cleanup

  • Use useEffect for cleanup operations, such as clearing intervals or canceling subscriptions.
import React, { useEffect, useState } from 'react';

const IntervalComponent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCount(prevCount => prevCount + 1);
    }, 1000);

    return () => {
      // Cleanup: clearInterval on component unmount
      clearInterval(intervalId);
    };
  }, []); // Empty dependency array means useEffect runs once after the initial render

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
};

Dependency Array

  • The dependency array in useEffect determines when the effect runs.
  • If the dependencies change between renders, the effect runs.
useEffect(() => {
  // Effect runs when dependencies change
}, [dependency1, dependency2]);

Effect without Cleanup

  • If the effect doesn't require cleanup, you can omit the return statement.
useEffect(() => {
  // Side effect code without cleanup
}, [dependencies]);

 

Summary

useEffect is a powerful tool for managing side effects in functional components. It contributes to a cleaner and more efficient code structure in React applications.