What is useEffect in React?

useEffect is a built-in hook in React that allows you to perform side effects in functional components. Side effects can include things like fetching data from an API, updating the DOM, or subscribing to events. The useEffect hook takes two arguments: a function that performs the side effect, and an optional array of dependencies that determines when the effect should be re-run. When a component mounts, useEffect runs the function once. If the dependencies array is provided, useEffect will re-run the function when any of the dependencies change.

Below are some examples of using the useEffect.

Example 1: Fetching data from an API:

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <ul>
      {data.map(item => <li key={item.id}>{item.name}</li>)}
    </ul>
  );
}

In this example, we start by importing useState and useEffect from the react module. We then define a functional component called MyComponent that initializes a state variable called data to an empty array.

Inside the useEffect hook, we use the fetch API to make a GET request to an external API that returns some data. We then call the setData function to update the state with the new data.

Finally, we render the data as a list of items.

Note that we pass an empty array ([]) as the second argument to useEffect. This tells React that we only want to fetch the data once, when the component mounts.

Example 2: Updating the document title.

import { useEffect } from 'react';

function MyComponent({ title }) {
  useEffect(() => {
    document.title = title;
  }, [title]);

  return <h1>{title}</h1>;
}


In this example, we define a functional component called MyComponent that takes a title prop. Inside the useEffect hook, we update the document title to match the value of the title prop. We also pass [title] as the second argument to useEffect, which tells React to re-run the effect whenever the title prop changes.

Finally, we render the title as an <h1> element.

Example 3: Subscribing to events.

import { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const handleClick = () => setCount(count + 1);
    window.addEventListener('click', handleClick);
    return () => window.removeEventListener('click', handleClick);
  }, [count]);

  return <p>You clicked {count} times.</p>;
}


In this example, we define a functional component called MyComponent that initializes a state variable called count to zero.

Inside the useEffect hook, we define a function called handleClick that increments the count state variable. We then add an event listener to the window object that listens for clicks and calls handleClick.

We also return a cleanup function from useEffect that removes the event listener when the component unmounts or when the count state variable changes (this is because handleClick references count, so we need to make sure we’re always using the latest value).

Finally, we render the current count as a paragraph element.

Happy Learning …