react-intersection-observer vs react-scroll vs react-scrollspy vs react-waypoint
React Scroll and Intersection Libraries
react-intersection-observerreact-scrollreact-scrollspyreact-waypointSimilar Packages:

React Scroll and Intersection Libraries

React scroll and intersection libraries provide tools for handling scroll events, detecting when elements enter or leave the viewport, and creating smooth scrolling experiences in React applications. These libraries help developers implement features like lazy loading, infinite scrolling, scroll-based animations, and navigation highlighting with ease. They offer optimized and reusable components that handle the complexities of scroll event management, improving performance and user experience. By using these libraries, developers can create more interactive and responsive web applications that react to user scrolling behavior in a seamless and efficient manner.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-intersection-observer05,536168 kB012 days agoMIT
react-scroll04,400139 kB2292 years agoMIT
react-scrollspy0428-846 years agoMIT
react-waypoint04,04060.7 kB59-MIT

Feature Comparison: react-intersection-observer vs react-scroll vs react-scrollspy vs react-waypoint

Viewport Detection

  • react-intersection-observer:

    react-intersection-observer uses the Intersection Observer API to detect when elements enter or leave the viewport. This approach is highly efficient and minimizes the performance impact compared to traditional scroll event listeners.

  • react-scroll:

    react-scroll does not provide viewport detection out of the box. It focuses on animating scroll events rather than detecting element visibility.

  • react-scrollspy:

    react-scrollspy detects the current scroll position and highlights navigation items based on which section is visible. It uses scroll event listeners to track the user's position on the page.

  • react-waypoint:

    react-waypoint allows you to define waypoints in your application and trigger callbacks when the user scrolls to those points. It is a simple and flexible way to detect scroll positions without a lot of complexity.

Smooth Scrolling

  • react-intersection-observer:

    react-intersection-observer does not handle smooth scrolling. It is focused on detecting element visibility rather than animating scroll behavior.

  • react-scroll:

    react-scroll specializes in smooth scrolling animations. It provides a variety of options for customizing the scroll behavior, including duration, easing, and offset.

  • react-scrollspy:

    react-scrollspy does not handle smooth scrolling. It is designed to update navigation items based on scroll position, but it does not animate the scrolling itself.

  • react-waypoint:

    react-waypoint does not provide smooth scrolling functionality. It is focused on triggering events at specific scroll positions rather than animating the scroll.

Navigation Highlighting

  • react-intersection-observer:

    react-intersection-observer can be used to implement navigation highlighting by detecting when sections enter the viewport. However, this functionality is not built-in and requires custom implementation.

  • react-scroll:

    react-scroll does not provide navigation highlighting out of the box. It focuses on animating scroll events, but you can combine it with other libraries or custom code to highlight navigation items.

  • react-scrollspy:

    react-scrollspy is specifically designed for navigation highlighting. It automatically updates the active class on navigation items based on the current scroll position, making it easy to create interactive menus.

  • react-waypoint:

    react-waypoint can be used to implement navigation highlighting by triggering callbacks when the user scrolls to specific sections. However, this functionality is not built-in and requires custom implementation.

Performance

  • react-intersection-observer:

    react-intersection-observer is highly performant due to its use of the Intersection Observer API, which is optimized for detecting visibility changes without causing layout thrashing or excessive reflows.

  • react-scroll:

    react-scroll is generally performant, but smooth scrolling animations can impact performance if overused or implemented on very large pages. It is important to use it judiciously to avoid jank.

  • react-scrollspy:

    react-scrollspy relies on scroll event listeners, which can impact performance if not throttled or debounced. However, it is lightweight and efficient for most typical use cases.

  • react-waypoint:

    react-waypoint is designed to be lightweight and efficient. It minimizes the performance impact by only triggering callbacks when the user scrolls to defined waypoints, rather than continuously listening to scroll events.

Ease of Use: Code Examples

  • react-intersection-observer:

    react-intersection-observer provides a simple API for detecting element visibility. It integrates seamlessly with React hooks and components, making it easy to use for lazy loading and animations.

    Example:

    import { useInView } from 'react-intersection-observer';
    
    function LazyImage() {
      const { ref, inView } = useInView({
        triggerOnce: true,
        threshold: 0.1,
      });
    
      return (
        <div ref={ref}>
          {inView ? <img src="image.jpg" alt="Lazy Loaded" /> : <div>Loading...</div>}
        </div>
      );
    }
    
  • react-scroll:

    react-scroll offers a straightforward API for creating smooth scrolling links and animations. It is well-documented and easy to integrate into existing projects.

    Example:

    import { Link, animateScroll as scroll } from 'react-scroll';
    
    function Navbar() {
      return (
        <nav>
          <Link to="section1" smooth={true} duration={500}>
            Section 1
          </Link>
          <Link to="section2" smooth={true} duration={500}>
            Section 2
          </Link>
        </nav>
      );
    }
    
  • react-scrollspy:

    react-scrollspy is simple to use for highlighting navigation items based on scroll position. It requires minimal setup and works well with existing navigation components.

    Example:

    import Scrollspy from 'react-scrollspy';
    
    function Navbar() {
      return (
        <Scrollspy items={["section1", "section2"]} currentClassName="active">
          <li><a href="#section1">Section 1</a></li>
          <li><a href="#section2">Section 2</a></li>
        </Scrollspy>
      );
    }
    
  • react-waypoint:

    react-waypoint provides a simple interface for defining waypoints and triggering callbacks. It is easy to use and integrates well with React components.

    Example:

    import { Waypoint } from 'react-waypoint';
    
    function InfiniteScrollList({ loadMore }) {
      return (
        <div>
          {/* List items */}
          <Waypoint onEnter={loadMore} />
        </div>
      );
    }
    

How to Choose: react-intersection-observer vs react-scroll vs react-scrollspy vs react-waypoint

  • react-intersection-observer:

    Choose react-intersection-observer if you need a lightweight and efficient way to detect when elements enter or leave the viewport. It is ideal for implementing lazy loading, animations, and other scroll-based interactions with minimal performance impact.

  • react-scroll:

    Choose react-scroll if you want to create smooth scrolling effects and handle scroll events programmatically. It is perfect for single-page applications, landing pages, and any project that requires animated scrolling to specific sections.

  • react-scrollspy:

    Choose react-scrollspy if you need to highlight navigation items based on the current scroll position. It is useful for creating table of contents, sidebars, and other navigation components that update as the user scrolls through the page.

  • react-waypoint:

    Choose react-waypoint if you need a simple and flexible way to trigger functions when scrolling to specific points on the page. It is great for implementing infinite scrolling, lazy loading, and other scroll-based interactions without a lot of overhead.

README for react-intersection-observer

React Intersection Observer

Version Badge Test License Downloads npm package minimized gzipped size

A React implementation of the Intersection Observer API that tells you when an element enters or leaves the viewport. Use it for scroll animations, lazy loading, impression tracking, and infinite scroll. It ships hooks, render props, and plain children.

Features

  • Hooks or component API - useInView for React state, useOnInView for callbacks, <InView> for render props and wrapper elements.
  • Shared observers - Observers with matching options are reused, so watching many elements stays cheap.
  • Matches the native API - Options map straight to IntersectionObserverInit.
  • Written in TypeScript - Types ship with the package.
  • Ready to test - Mocks the Intersection Observer for Jest and Vitest.
  • Tree-shakeable - Only the parts you import end up in your bundle.
  • Small - Around 1.15kB gzipped for useInView, 1.6kB for <InView>.

Open in StackBlitz

Installation

npm install react-intersection-observer --save

Usage

useInView hook

// Use object destructuring, so you don't need to remember the exact order
const { ref, inView, entry } = useInView(options);

// Or array destructuring, making it easy to customize the field names
const [ref, inView, entry] = useInView(options);

Call useInView with the (optional) options you need. It returns a ref, the inView status, and the current entry. Assign the ref to the DOM element you want to watch, and the hook reports the status.

import React from "react";
import { useInView } from "react-intersection-observer";

const Component = () => {
  const { ref, inView, entry } = useInView({
    /* Optional options */
    threshold: 0,
  });

  return (
    <div ref={ref}>
      <h2>{`Header inside viewport ${inView}.`}</h2>
    </div>
  );
};

Note: The first false notification from the underlying IntersectionObserver is ignored so your handlers only run after a real visibility change. Subsequent transitions still report both true and false states as the element enters and leaves the viewport.

useOnInView hook

const inViewRef = useOnInView(
  (inView, entry) => {
    if (inView) {
      // Do something with the element that came into view
      console.log("Element is in view", entry.target);
    } else {
      console.log("Element left view", entry.target);
    }
  },
  options // Optional IntersectionObserver options
);

useOnInView takes a callback and returns a ref to assign to the DOM element you want to watch. Whenever the element enters or leaves the viewport, the callback runs with the latest in-view state.

Differences from useInView:

  • No re-renders - The hook holds no state, so a visibility change never triggers a render.
  • Direct element access - The callback receives the IntersectionObserverEntry, including the target element.
  • Boolean-first callback - The first argument is the current inView boolean, matching the onChange signature from useInView.
  • Same options - Accepts every option useInView does, except onChange, initialInView, and fallbackInView.

Note: Just like useInView, the initial false notification is skipped. Your callback fires the first time the element becomes visible, then on every enter and leave transition after that.

import React from "react";
import { useOnInView } from "react-intersection-observer";

const Component = () => {
  // Track when element appears without causing re-renders
  const trackingRef = useOnInView(
    (inView, entry) => {
      if (inView) {
        // Element is in view, so log an impression
        console.log("Element appeared in view", entry.target);
      } else {
        console.log("Element left view", entry.target);
      }
    },
    {
      /* Optional options */
      threshold: 0.5,
      triggerOnce: true,
    },
  );

  return (
    <div ref={trackingRef}>
      <h2>This element is being tracked without re-renders</h2>
    </div>
  );
};

Render props

Pass <InView> a function. It runs whenever the state changes, with the new value of inView. Children also receive a ref that you set on the containing DOM element. That element is the one the Intersection Observer watches.

The IntersectionObserverEntry is available on entry when you need the details of the current intersection state.

import { InView } from "react-intersection-observer";

const Component = () => (
  <InView>
    {({ inView, ref, entry }) => (
      <div ref={ref}>
        <h2>{`Header inside viewport ${inView}.`}</h2>
      </div>
    )}
  </InView>
);

export default Component;

Note: <InView> behaves like the hooks. It suppresses the first false notification, so render props and onChange handlers only run after a real visibility change.

Plain children

Pass any element to <InView /> and it creates the wrapping DOM element for you. Add a handler to onChange and keep the state in your own component. Extra props on <InView> go to the HTML element, so you can set className, style, and the rest.

import { InView } from "react-intersection-observer";

const Component = () => (
  <InView as="div" onChange={(inView, entry) => console.log("Inview:", inView)}>
    <h2>Plain children are always rendered. Use onChange to monitor state.</h2>
  </InView>
);

export default Component;

[!NOTE] When rendering a plain child, keep your HTML output semantic. Change as to match the context, and add a className to style the <InView />. The component does not forward refs, so use the render props version if you need a ref to the HTML element.

API

Options

Pass these as the options argument to useInView, or as props on <InView />.

NameTypeDefaultDescription
rootElementdocumentThe element whose bounds count as the viewport for the target. It must be an ancestor of the target. With null, the document viewport is used.
rootMarginstring'0px'Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). Also supports percentages, to check if an element intersects with the center of the viewport for example "-50% 0% -50% 0%".
scrollMarginstring'0px'Margin around nested scroll containers that clip the target. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). Unlike rootMargin, this grows or shrinks every scroll container's clipping rectangle within the root, including the root itself if it is a scroll container.
thresholdnumber or number[]0Number between 0 and 1 indicating the percentage that should be visible before triggering. Can also be an array of numbers, to create multiple trigger points.
onChange(inView, entry) => voidundefinedRuns whenever the in view state changes, with the inView boolean and the current IntersectionObserverEntry.
trackVisibilitybooleanfalseExperimental. Track visibility changes on the target, beyond plain intersection. See Intersection Observer v2.
delaynumberundefinedExperimental. Minimum delay in milliseconds between notifications for a given target. Must be at least 100 if trackVisibility is true.
skipbooleanfalseSkip creating the IntersectionObserver, so you can turn observation on and off. Setting skip while inView keeps the current state.
triggerOncebooleanfalseOnly trigger the observer once.
initialInViewbooleanfalseThe starting value of inView. Set it to true when the element starts in the viewport and you want to trigger something when it leaves.
fallbackInViewbooleanundefinedThe inView value to use when the client has no IntersectionObserver, instead of the default behavior of throwing. defaultFallbackInView() sets this globally.

useOnInView accepts the same options as useInView except onChange, initialInView, and fallbackInView.

InView props

The <InView /> component also accepts the following props:

NameTypeDefaultDescription
asIntrinsicElement'div'Render the wrapping element as this element. Defaults to div. If you want to use a custom component, use the useInView hook or a render prop instead to manage the reference explicitly.
children({ref, inView, entry}) => ReactNode or ReactNodeundefinedA function receiving inView, a ref to assign to the element root, and the IntersectionObserverEntry as entry. Pass a plain child instead to let <InView /> create the wrapping element.

Intersection Observer v2

Intersection Observer v2 extends the original API, so you can track whether the element is covered by another element or has filters applied to it. Useful for blocking clickjacking attempts or tracking ad exposure.

Add the trackVisibility and delay options, then check whether isVisible is true on the entry you get back.

const TrackVisible = () => {
  const { ref, entry } = useInView({ trackVisibility: true, delay: 100 });
  return <div ref={ref}>{entry?.isVisible}</div>;
};

Check caniuse for current browser support. If you set trackVisibility and the browser doesn't support it, the fallback always reports isVisible as true.

isVisible isn't in the TypeScript lib.d.ts file yet, so you also have to extend IntersectionObserverEntry with the boolean yourself.

Recipes

A few things you can build with it:

FAQ

How can I assign multiple refs to a component?

You can wrap multiple ref assignments in a single useCallback:

import React, { useRef, useCallback } from "react";
import { useInView } from "react-intersection-observer";

function Component(props) {
  const ref = useRef();
  const { ref: inViewRef, inView } = useInView();

  // Use `useCallback` so we don't recreate the function on each render
  const setRefs = useCallback(
    (node) => {
      // Refs from `useRef` need the node assigned to `current`
      ref.current = node;
      // Callback refs, like the one from `useInView`, are functions that take the node
      inViewRef(node);
    },
    [inViewRef],
  );

  return <div ref={setRefs}>Shared ref is visible: {inView}</div>;
}

rootMargin isn't working as expected

rootMargin is added to the current root. If your application runs inside an <iframe>, or you defined a custom root, that root is not the viewport.

If a scrollable container inside the root clips the target, use scrollMargin to change when intersections are calculated for that nested scroll container.

More background:

Testing

[!TIP] Consider using Vitest Browser Mode instead of jsdom or happy-dom. It runs the browser's own implementation, so intersections trigger correctly when you scroll or add elements to the viewport. You can skip react-intersection-observer/test-utils there, or use it where you need it.

To write meaningful tests, mock the IntersectionObserver. The included react-intersection-observer/test-utils does that, and adds a few methods for faking the inView state. Pass isIntersecting either a boolean or a threshold between 0 and 1; the mock emulates the real IntersectionObserver so you can check that your components behave as expected.

MethodDescription
mockAllIsIntersecting(isIntersecting)Set isIntersecting on every current Intersection Observer instance. Pass a boolean or a threshold between 0 and 1.
mockIsIntersecting(element, isIntersecting)Set isIntersecting for the Intersection Observer of one element. Pass a boolean or a threshold between 0 and 1.
intersectionMockInstance(element)Get the mocked IntersectionObserver instance for an element, so you can spy on its observe and unobserve methods.
setupIntersectionMocking(mockFn)Mock the IntersectionObserver. Call it in beforeEach. (Happens automatically in a Jest environment.)
resetIntersectionMocking()Reset the mocks on IntersectionObserver. Call it in afterEach. (Happens automatically in a Jest or Vitest environment.)
destroyIntersectionMocking()Destroy the mock and restore the browser's own window.IntersectionObserver.

Testing libraries

The test utilities work with both Jest and Vitest.

Jest

Jest works out of the box. Import react-intersection-observer/test-utils in your test files and use the mocking methods.

Vitest

With Vitest globals enabled, the IntersectionObserver is mocked automatically, just like in Jest. Otherwise, set up and reset the mocking yourself, either in individual tests or in a setup file.

import { vi, beforeEach, afterEach } from "vitest";
import {
  setupIntersectionMocking,
  resetIntersectionMocking,
} from "react-intersection-observer/test-utils";

beforeEach(() => {
  setupIntersectionMocking(vi.fn);
});

afterEach(() => {
  resetIntersectionMocking();
});

You only need this if the test environment doesn't expose beforeEach globally alongside either jest.fn or vi.fn.

Other testing libraries

Follow the Vitest instructions. The same setup and reset code should work, adapted to your test runner. Failing that, copy test-utils.ts and make your own version.

Fallback behavior

You can create a Jest setup file that uses the unsupported fallback option, then override the IntersectionObserver in the test files where you import react-intersection-observer/test-utils.

test-setup.js

import { defaultFallbackInView } from "react-intersection-observer";

defaultFallbackInView(true); // or `false`, whichever is right for your app

To mock the Intersection Observer in every test instead, use a global setup file. Add react-intersection-observer/test-utils to setupFilesAfterEnv in the Jest config, or setupFiles in Vitest.

module.exports = {
  setupFilesAfterEnv: ["react-intersection-observer/test-utils"],
};

Test example

import React from "react";
import { screen, render } from "@testing-library/react";
import { useInView } from "react-intersection-observer";
import {
  mockAllIsIntersecting,
  mockIsIntersecting,
  intersectionMockInstance,
} from "react-intersection-observer/test-utils";

const HookComponent = ({ options }) => {
  const { ref, inView } = useInView(options);
  return (
    <div ref={ref} data-testid="wrapper">
      {inView.toString()}
    </div>
  );
};

test("should create a hook inView", () => {
  render(<HookComponent />);

  // This causes all (existing) IntersectionObservers to be set as intersecting
  mockAllIsIntersecting(true);
  screen.getByText("true");
});

test("should create a hook inView with threshold", () => {
  render(<HookComponent options={{ threshold: 0.3 }} />);

  mockAllIsIntersecting(0.1);
  screen.getByText("false");

  // Once the threshold has been passed, it will trigger inView.
  mockAllIsIntersecting(0.3);
  screen.getByText("true");
});

test("should mock intersecting on a specific hook", () => {
  render(<HookComponent />);
  const wrapper = screen.getByTestId("wrapper");

  // Set the intersection state on the wrapper.
  mockIsIntersecting(wrapper, 0.5);
  screen.getByText("true");
});

test("should create a hook and call observe", () => {
  const { getByTestId } = render(<HookComponent />);
  const wrapper = getByTestId("wrapper");
  // Access the `IntersectionObserver` instance for the wrapper Element.
  const instance = intersectionMockInstance(wrapper);

  expect(instance.observe).toHaveBeenCalledWith(wrapper);
});

Intersection Observer

Intersection Observer is the API used to determine whether an element is inside the viewport. Every major browser supports it natively, Safari since 12.1. Add the polyfill if you still support older iOS versions or IE11.

Unsupported fallback

If the client has no IntersectionObserver, the default behavior is to throw an error. That crashes the React application unless an Error Boundary catches it.

You can instead set a fallback inView value to use when IntersectionObserver doesn't exist. Make sure your application handles every observer firing true (or false) at the same time.

You can set the fallback globally:

import { defaultFallbackInView } from "react-intersection-observer";

defaultFallbackInView(true); // or 'false'

You can also set the fallback locally on useInView or <InView>. A local value overrides the global one.

import React from "react";
import { useInView } from "react-intersection-observer";

const Component = () => {
  const { ref, inView, entry } = useInView({
    fallbackInView: true,
  });

  return (
    <div ref={ref}>
      <h2>{`Header inside viewport ${inView}.`}</h2>
    </div>
  );
};

Polyfill

Import the polyfill directly, or use a service like cdnjs.cloudflare.com/polyfill to add it when needed.

yarn add intersection-observer

Then import it in your app:

import "intersection-observer";

With Webpack or a similar bundler, use dynamic imports to load the polyfill only when it's needed:

/**
 * Feature detection, to figure out which polyfills need importing.
 **/
async function loadPolyfills() {
  if (typeof window.IntersectionObserver === "undefined") {
    await import("intersection-observer");
  }
}

Low-level API

The observe method is the one react-intersection-observer uses internally to create and destroy IntersectionObserver instances. Use it when you need full control over when and how observers are created.

import { observe } from "react-intersection-observer";

const destroy = observe(element, callback, options);
NameTypeRequiredDescription
elementElementtrueDOM element to observe
callbackObserverInstanceCallbacktrueThe callback function that Intersection Observer will call
optionsIntersectionObserverInitfalseThe options for the Intersection Observer

observe returns an unobserve function. Call it to destroy the observer again.

[!IMPORTANT] You most likely won't need this. It's here for handling IntersectionObservers outside React, or when you need full control over how instances are created.