Explain Codes LogoExplain Codes Logo

Infinite scrolling with React JS

javascript
infinite-scrolling
react-js
virtualization
Alex KataevbyAlex Kataev·Jan 27, 2025
TLDR

Infinite scrolling in React can be achieved by leveraging the Intersection Observer API for efficient loading. Here’s a straightforward example:

import React, { useState, useRef, useCallback } from 'react'; function InfiniteScrollList() { const [items, setItems] = useState([]); const observer = useRef(); const lastItemRef = useCallback(node => { // create our mimic scroll icon (⛷️) if (observer.current) observer.current.disconnect(); observer.current = new IntersectionObserver(entries => { if (entries[0].isIntersecting) { // Now this ⛷️ hits the last item. Load your next payload here // and append to 'items'. Replace newItems as required. setItems(prevItems => [...prevItems, ...newItems]); } }); if (node) observer.current.observe(node); // Skiing starts here 😉 }, []); return ( <ul> {items.map((item, index) => ( <li ref={index + 1 === items.length ? lastItemRef : null} key={item.id}> {item.content} </li> ))} </ul> ); }

Key steps: Use useCallback with a ref to mark the last item. The magic happens when IntersectionObserver sees our skiing ⛷️ reaching this item and loads the next set. Time to replace the value in setItems with your data fetching logic.

Using spacers for offscreen items

That gigantic list can be tackled smartly by substitizing offscreen elements with spacers. This method holds the DOM lean and facilitates smoother scrolling performance.

DOM element management

Keeping your DOM weight in check is key. Stick to a 50 elements rule: handle DOM items dynamically, loading and unloading content during scrolling. This technique ensures low memory footprint and high responsiveness.

State management for optimal rendering

For an optimized render, maintain a range of currently visible rows in the state of the component. This reduces unnecessary rendering calls and paves way for a smooth scrolling experience.

Bi-directional infinite scrolling

When an advanced case arises where the user browses both upcoming and previous content, apply bi-directional infinite scrolling. This proves helpful in cases where content timeline stretches in both new and old directions.

Visualization

Here's a simple depiction:

🚂 (Your Infinite Scroller) + 🛤️ (User's endless content journey)

Loading new content... = Train (🚂) picking up goods at every station (🚉)

Loading... 🚂 ===> 📦🚉...Loading... 🚂 ===> 📦🚉📦 ===> 📦🚉📦📦

Each 📦 is a payload, or batch of fresh content loaded during scroll.

So, user experience is like a never-ending smooth journey with new stories (📜) popping up as users scroll down the line (🛤️)_

React's virtualization libraries

Harnessing react-virtualized

When handling a large amount of data, react-virtualized provides complete solutions for virtualized lists, grids, and tables, thus boosting scrolling efficiency. Utilize its CellMeasurer for variable height calculations.

The lean react-window

If basic virtualization is all you need, check out react-window. This lightweight library maintains swift scrolling operations even with a massive amount of data.

Choosing the best library

Remember, it is paramount to pick the right tool for the job. Not every library supports maintaining an exact number of DOM elements. Weigh aspects such as memory efficiency, DOM management, and specific requirements of your project before you make a choice.

Scooping insights from ReactJS discussion threads

To learn and adapt, go through other developers' experiences and solutions regarding Bi-directional infinite scrolling on ReactJS forums. This can assist you in making practical, user-friendly infinite scrolling interfaces.

Variables to consider in sizing items

Bring in the CellMeasurer

When dealing with items of varying sizes on your plasma screen (inside joke for developers 😉), CellMeasurer from react-virtualized comes in handy for accurate size computation.

Gaining speed with measurement caching

Remember, caching measurements saves time. As users scroll, you can retain computed values for future use, therefore preventing redoing calculations during future scrolls, a formidable way to save computational resources.

Customizing react-window

When utilizing react-window, you might face a situation where elements differ in size. If this occurs, don’t panic; just use the library's dynamic list options. It'll measure cell sizes like a pro.