Blog>
Snippets

Fetching Data on Scroll with useEffect and useState

Demonstrate fetching data incrementally on scroll events in a React component using useEffect for side effects and useState to store the fetched data.
import React, { useEffect, useState } from 'react';
Imports react, useEffect, and useState from the 'react' library.
const InfiniteScrollComponent = () => {
Defines the functional component for infinite scroll.
  const [data, setData] = useState([]);
Defines state 'data' to store fetched items, initially an empty array.
  const fetchData = async () => {
Defines the fetchData asynchronous function to fetch data.
    // simulate fetching data from an API
Comments indicating the simulation of a data fetch.
    const newData = await fetch('https://example.com/api/items').then(res => res.json());
Fetches data from an example API and awaits its JSON response.
    setData(prevData => [...prevData, ...newData]);
Updates the 'data' state by appending new data to previous data.
  };
Closes the fetchData function.
  useEffect(() => {
Uses the useEffect hook for side effects.
    const handleScroll = () => {
Defines the scroll event handler function.
      if (window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) {
Checks if the user has scrolled to the bottom of the document.
        fetchData();
Calls fetchData function to load more data.
      }
Closes the if condition.
    };
Closes the handleScroll function.
    window.addEventListener('scroll', handleScroll);
Adds a 'scroll' event listener to the window object to trigger handleScroll.
    return () => window.removeEventListener('scroll', handleScroll);
Removes the event listener on component unmount to prevent memory leaks.
  }, []); // Dependency array is empty, so this useEffect runs only once, akin to componentDidMount
Closes the useEffect block.
  return ( <div>{data.map(item => <p key={item.id}>{item.title}</p>)}</div> );
Returns the JSX to render, mapping each item in data to a paragraph.
};
Closes the InfiniteScrollComponent functional component.
export default InfiniteScrollComponent;
Exports the InfiniteScrollComponent for use in other parts of the application.