React useEffect Hook Example


In React, components are the building blocks of user interfaces, and they can have side effects outside the rendering process. Side effects can include data fetching, subscriptions, or manually manipulating the DOM. The useEffect hook provides a way to handle these side effects in a declarative manner. In this blog, we’ll explore the useEffect hook in-depth, and understand its purpose with examples to help you grasp its usage.

Syntax and Dependencies

The useEffect hook takes two arguments: a callback function and an array of dependencies.

useEffect(() => {
  // Side effect code goes here
}, [dependencies]);

The callback function contains the code that executes the side effect. It can be an asynchronous function, a subscription setup, or any other code that needs to be executed after the component renders. The array of dependencies is an optional parameter that specifies when the effect should re-run. If the array is empty, the effect only runs once, after the initial render.

Let’s have a look at the practical examples of useEffect hook in react.

1. Fetching Data from an API

In the below example, the useEffect hook is used to fetch data from an API. The effect runs only once, after the initial render, indicated by the empty dependency array. The fetched data is stored in the component’s state using the useEffect hook.

DataFetching.js
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const jsonData = await response.json();
      setData(jsonData);
    };

    fetchData();
  }, []);

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

Similar Post: React useState Hook Example

2. Subscribing to Event Listeners

Here, the useEffect hook is used to subscribe to a click event listener on the document. The effect runs once, after the initial render, and adds the event listener. The cleanup function returned by the effect removes the event listener when the component is unmounted.

EventListenerExample.js
import React, { useEffect } from 'react';

function EventListenerExample() {
  useEffect(() => {
    const handleClick = () => {
      console.log('Button clicked!');
    };

    document.addEventListener('click', handleClick);

    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, []);

  return <button>Click me</button>;
}

3. Manipulating the DOM

In this example, the useEffect hook is used to manipulate the DOM based on the window’s scroll position. The effect runs once, after the initial render, and adds a scroll event listener. The cleanup function removes the event listener when the component is unmounted.

ScrollToTopButton.js
import React, { useEffect } from 'react';

function ScrollToTopButton() {
  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 500) {
        // Display the "Scroll to top" button
      } else {
        // Hide the button
      }
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return <button>Scroll to top</button>;
}

References

  1. useEffect Hooks- React
  2. How to consume REST APIs in React using Axios
  3. How to call a REST API in React
  4. Top 5 React Hooks

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.