These four libraries solve the problem of reacting to scroll events, but they approach it from fundamentally different angles. react-intersection-observer wraps the modern browser Intersection Observer API to detect when elements enter or leave the viewport with high performance. react-scroll provides a suite of components for smooth scrolling animations and spy-based navigation linking. react-scrollspy is a specialized component specifically for highlighting navigation links based on the current scroll position. react-waypoint acts as a sentinel, triggering callbacks only when an element crosses a specific boundary line within its container. While react-scroll and react-scrollspy focus on UI polish and navigation state, react-intersection-observer and react-waypoint focus on precise geometric detection for logic triggers.
When building scroll-driven interfaces, developers often face a choice between detecting visibility, animating movement, or tracking navigation state. The packages react-intersection-observer, react-scroll, react-scrollspy, and react-waypoint each solve these problems differently. Understanding their underlying mechanisms is crucial for avoiding performance bottlenecks and choosing the right tool for your architecture.
The most critical technical distinction lies in how these libraries detect movement. Modern browsers provide the Intersection Observer API, which is highly performant because it runs asynchronously and doesn't block the main thread during scroll events.
react-intersection-observer is a thin wrapper around this native API. It does not listen to the scroll event directly. Instead, it asks the browser to notify it when an element intersects with a viewport.
// react-intersection-observer: Uses native Intersection Observer
import { useInView } from 'react-intersection-observer';
function LazyImage() {
const { ref, inView } = useInView({
threshold: 0.5, // Trigger when 50% visible
});
return <img ref={ref} src={inView ? 'image.jpg' : 'placeholder.jpg'} />;
}
react-waypoint also avoids direct scroll listeners where possible but focuses on "waypoints" — specific boundaries. It calculates positions relative to a container and fires callbacks when an element crosses that line. It is particularly robust when dealing with dynamic content heights.
// react-waypoint: Triggers on crossing a boundary
import Waypoint from 'react-waypoint';
function InfiniteList() {
const handleEnter = () => console.log('Entered waypoint');
const handleLeave = () => console.log('Left waypoint');
return (
<Waypoint onEnter={handleEnter} onLeave={handleLeave}>
<div>Load more content here</div>
</Waypoint>
);
}
In contrast, react-scroll and react-scrollspy traditionally rely on listening to the window's scroll event. They calculate element positions manually on every tick. While they may include optimization techniques (like throttling), this approach is inherently more expensive than the Observer API, especially on mobile devices with complex layouts.
// react-scroll: Relies on scroll event listeners for linking
import { Link, Element } from 'react-scroll';
function Navigation() {
return (
<nav>
<Link to="section1" smooth={true} duration={500}>Go to Section 1</Link>
<Element name="section1" className="section">
<h1>Section 1</h1>
</Element>
</nav>
);
}
// react-scrollspy: Listens to scroll to update active state
import Scrollspy from 'react-scrollspy';
function Menu() {
return (
<Scrollspy items={['section1', 'section2']} currentClassName="active">
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
</ul>
</Scrollspy>
);
}
A major functional divide exists between packages that move the page and those that simply watch it.
react-scroll is the only package in this group primarily designed to animate the scroll position. It provides a smooth prop that interpolates the scroll position over time. This is essential for single-page applications where jumping instantly to an anchor feels jarring.
// react-scroll: Built-in smooth animation
<Link to="contact" smooth={true} offset={-70} duration={1000}>
Contact Us
</Link>
react-intersection-observer, react-waypoint, and react-scrollspy do not perform scrolling animations. They are passive observers. If you need smooth scrolling with react-intersection-observer, you must pair it with a separate utility or native CSS behavior (scroll-behavior: smooth).
// react-intersection-observer: Passive detection only
// You must handle the scroll action yourself if needed
const { ref } = useInView();
<div ref={ref}>I am being watched, but I don't move the page.</div>
For building sticky headers or navigation bars that highlight the current section, the approach differs significantly.
react-scrollspy is a dedicated solution for this specific pattern. It takes a list of item IDs and automatically manages the className of the navigation links based on the scroll position. It reduces boilerplate but offers less flexibility if your navigation logic is complex (e.g., non-linear sections).
// react-scrollspy: Automated link highlighting
<Scrollspy
items={['intro', 'features', 'pricing']}
currentClassName="is-active"
offset={-100}
>
<nav>
<a href="#intro">Intro</a>
<a href="#features">Features</a>
<a href="#pricing">Pricing</a>
</nav>
</Scrollspy>
react-scroll offers similar "spy" functionality via its spy prop on the Link component. This allows you to mix scrolling actions and spy behavior in the same component tree, which can be convenient but ties your navigation logic tightly to the scrolling library.
// react-scroll: Spy behavior on Link components
<Link to="features" spy={true} smooth={true} offset={-70}>
Features
</Link>
react-intersection-observer requires you to build the navigation state manually. While this requires more code, it gives you full control. You can track multiple sections simultaneously and update a global state (like Redux or Context) without relying on the library's internal logic.
// react-intersection-observer: Manual state management for nav
const [activeSection, setActiveSection] = useState('');
const Section = ({ id }) => {
const { ref, inView } = useInView({ threshold: 0.5 });
useEffect(() => {
if (inView) setActiveSection(id);
}, [inView, id]);
return <section ref={ref} id={id}>...</section>;
};
When content loads dynamically (e.g., images loading late, ads injecting content), scroll calculations can break.
react-waypoint excels here. Because it calculates positions relative to its immediate parent and re-evaluates when the DOM changes, it is very reliable for "Infinite Scroll" patterns where new items are prepended or appended.
// react-waypoint: Reliable for infinite lists
{items.map(item => <Item key={item.id} data={item} />)}
<Waypoint onEnter={() => loadMoreItems()} />
react-scroll and react-scrollspy can suffer from "drift" if the page layout shifts after the initial calculation. If an image loads and pushes content down, the stored scroll offsets might become inaccurate until the next scroll event recalculates them. This can cause the wrong navigation link to appear active.
react-intersection-observer is immune to most layout shift issues because the browser's Observer API automatically re-calculates intersections whenever the DOM mutates. This makes it the safest choice for modern, dynamic web apps.
It is vital to note the maintenance status of these libraries before adoption.
react-scrollspy: This package has seen very infrequent updates in recent years and has open issues regarding React 18 compatibility and SSR hydration mismatches. It is often considered legacy. For new projects, developers are encouraged to replicate its functionality using react-intersection-observer hooks to ensure long-term stability.react-scroll: While still popular, it relies heavily on older patterns. It works, but the community trend is moving towards native CSS scroll-behavior for animations and custom hooks for spy logic to reduce bundle size.react-intersection-observer and react-waypoint: Both are actively maintained and align with modern React patterns (Hooks for the former, robust callbacks for the latter). They are the recommended choices for new architectural decisions.| Feature | react-intersection-observer | react-waypoint | react-scroll | react-scrollspy |
|---|---|---|---|---|
| Primary Use | Visibility Detection | Boundary Crossing | Smooth Scroll + Spy | Nav Highlighting |
| Performance | ⭐⭐⭐⭐⭐ (Native API) | ⭐⭐⭐⭐ (Optimized) | ⭐⭐⭐ (Scroll Listener) | ⭐⭐⭐ (Scroll Listener) |
| Smooth Scroll | ❌ (Manual/CSS) | ❌ (Manual/CSS) | ✅ (Built-in) | ❌ (Logic only) |
| Dynamic Content | ✅ (Auto-updates) | ✅ (Robust) | ⚠️ (Can drift) | ⚠️ (Can drift) |
| Maintenance | ✅ Active | ✅ Active | ⚠️ Stable/Legacy | ⚠️ Low Activity |
For modern applications, start with react-intersection-observer. Its use of the native API provides the best performance and reliability for 90% of use cases, such as lazy loading, analytics tracking, and trigger-based animations. Pair it with native CSS scroll-behavior: smooth if you need basic scrolling.
Use react-waypoint if you are building complex infinite lists or need to detect the exact moment an element leaves a container, especially in dynamic environments where content height changes frequently.
Reserve react-scroll for legacy projects or specific scenarios where you need a quick, all-in-one solution for smooth scrolling anchors and don't mind the extra bundle size of a scroll-listener-based approach. Avoid react-scrollspy in new projects; instead, build a custom hook using react-intersection-observer to manage navigation state, ensuring your app remains future-proof and performant.
Choose react-intersection-observer when you need to detect visibility for performance-critical tasks like lazy loading images, triggering animations, or infinite scrolling. It is the best choice for modern applications because it uses the native Intersection Observer API, avoiding the performance penalties of listening to raw scroll events. Use this if you need granular control over thresholds (e.g., 'trigger when 50% visible') and want a solution that works seamlessly with Server Side Rendering (SSR).
Choose react-scroll if your primary goal is to add smooth scrolling animations to anchor links and automatically highlight navigation items based on scroll position. This package is ideal for single-page landing pages or documentation sites where you want a 'scroll spy' behavior coupled with animated scrolling without writing custom math. Avoid this if you only need simple visibility detection without the animation overhead.
Choose react-scrollspy when you have a fixed navigation bar and need a lightweight, dedicated component to update the 'active' state of links as the user scrolls through sections. It is a narrower alternative to react-scroll if you do not need the smooth scrolling animation features and only care about the highlighting logic. This is suitable for simple section-based layouts where you want to minimize dependencies compared to the heavier react-scroll suite.
Choose react-waypoint when you need to trigger an action exactly at the moment an element crosses a specific boundary (entering or leaving), rather than just being 'visible'. It is excellent for infinite lists, loading more content as the user approaches the bottom, or tracking when a user leaves a specific section. Use this if you prefer a simple callback-based API over hooks and need reliable edge detection that works consistently across different container types.
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.
useInView for React state, useOnInView for
callbacks, <InView> for render props and wrapper elements.IntersectionObserverInit.useInView, 1.6kB for <InView>.npm install react-intersection-observer --save
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
falsenotification from the underlying IntersectionObserver is ignored so your handlers only run after a real visibility change. Subsequent transitions still report bothtrueandfalsestates as the element enters and leaves the viewport.
useOnInView hookconst 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:
IntersectionObserverEntry, including the target element.inView
boolean, matching the onChange signature from useInView.useInView does, except
onChange, initialInView, and fallbackInView.Note: Just like
useInView, the initialfalsenotification 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>
);
};
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 firstfalsenotification, so render props andonChangehandlers only run after a real visibility change.
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
asto match the context, and add aclassNameto style the<InView />. The component does not forward refs, so use the render props version if you need arefto the HTML element.
Pass these as the options argument to useInView, or as props on <InView />.
| Name | Type | Default | Description |
|---|---|---|---|
| root | Element | document | The 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. |
| rootMargin | string | '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%". |
| scrollMargin | string | '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. |
| threshold | number or number[] | 0 | Number 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) => void | undefined | Runs whenever the in view state changes, with the inView boolean and the current IntersectionObserverEntry. |
| trackVisibility | boolean | false | Experimental. Track visibility changes on the target, beyond plain intersection. See Intersection Observer v2. |
| delay | number | undefined | Experimental. Minimum delay in milliseconds between notifications for a given target. Must be at least 100 if trackVisibility is true. |
| skip | boolean | false | Skip creating the IntersectionObserver, so you can turn observation on and off. Setting skip while inView keeps the current state. |
| triggerOnce | boolean | false | Only trigger the observer once. |
| initialInView | boolean | false | The starting value of inView. Set it to true when the element starts in the viewport and you want to trigger something when it leaves. |
| fallbackInView | boolean | undefined | The 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.
The <InView /> component also accepts the following props:
| Name | Type | Default | Description |
|---|---|---|---|
| as | IntrinsicElement | '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 ReactNode | undefined | A 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 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.
A few things you can build with it:
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 expectedrootMargin 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:
[!TIP] Consider using Vitest Browser Mode instead of
jsdomorhappy-dom. It runs the browser's own implementation, so intersections trigger correctly when you scroll or add elements to the viewport. You can skipreact-intersection-observer/test-utilsthere, 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.
| Method | Description |
|---|---|
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. |
The test utilities work with both Jest and Vitest.
Jest works out of the box. Import react-intersection-observer/test-utils in
your test files and use the mocking methods.
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.
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.
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"],
};
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 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.
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>
);
};
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");
}
}
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);
| Name | Type | Required | Description |
|---|---|---|---|
| element | Element | true | DOM element to observe |
| callback | ObserverInstanceCallback | true | The callback function that Intersection Observer will call |
| options | IntersectionObserverInit | false | The 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.