useEffect hook in React

React’s useEffect hook is a powerful feature that allows us to handle side effects in functional components. Side effects can include things like fetching data from an API, subscribing to events, or manipulating the DOM.

The useEffect hook is similar to the lifecycle methods in class components, such as componentDidMount, componentDidUpdate, and componentWillUnmount. It allows you to perform side effects after the component has rendered or when certain dependencies have changed.

Basic Syntax

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Code to run after component has rendered
    // This function will be called on every render

    return () => {
      // Clean up code
      // This function will be called before the component is unmounted
    };
  }, []); // Optional dependencies array
}

The useEffect function takes two arguments:

Usage

Running Effects Once

To run an effect only once (similar to componentDidMount), you can pass an empty dependency array [] as the second argument to useEffect. This ensures that the effect runs only on the initial render.

useEffect(() => {
  // Code to run after component has rendered (only once)
}, []);

Running Effects on Dependency Change

You can specify an array of dependencies as the second argument to useEffect. This allows the effect to run whenever any of the dependencies change (similar to componentDidUpdate).

useEffect(() => {
  // Code to run after component has rendered or when dependencies change
}, [dependency1, dependency2]);

Cleaning Up Effects

The function returned from useEffect can be used to clean up any resources acquired by the effect (e.g., unsubscribe from events, cancel API requests). This function is called before the component is unmounted.

useEffect(() => {
  // Code to run after component has rendered

  return () => {
    // Clean up code
  };
}, []);

Conclusion

The useEffect hook is a powerful tool in React functional components for handling side effects. Its flexibility allows us to easily perform actions after the component renders or when specific dependencies change. Understanding how to use useEffect effectively can greatly enhance our React applications.