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

React Scroll and Intersection Libraries

These libraries are designed to enhance user experience in web applications by providing functionalities related to element visibility and scrolling behaviors. They allow developers to create dynamic and interactive interfaces that respond to user scrolling, making it easier to implement features like lazy loading, animations, and navigation highlights based on the user's viewport and scroll position.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-in-viewport0349110 kB2a year agoMIT
react-intersection-observer05,532164 kB217 days agoMIT
react-scroll04,420139 kB231a year agoMIT
react-scrollspy0426-846 years agoMIT
react-waypoint04,06160.7 kB59-MIT

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

Visibility Detection

  • react-in-viewport:

    react-in-viewport provides a simple way to detect when an element enters or exits the viewport. It uses a higher-order component to wrap your target elements, allowing you to easily manage visibility states and trigger actions based on whether the element is visible or not.

  • react-intersection-observer:

    react-intersection-observer utilizes the Intersection Observer API to efficiently monitor the visibility of multiple elements. This library is optimized for performance and can handle complex scenarios, such as lazy loading images or triggering animations when elements come into view, without the need for manual scroll event listeners.

  • react-scroll:

    react-scroll does not focus on visibility detection but rather on managing scroll behavior within a page. It allows you to create smooth scrolling effects and navigate between sections seamlessly, enhancing the overall user experience during scrolling actions.

  • react-scrollspy:

    react-scrollspy tracks the scroll position of the page and highlights the corresponding navigation links based on the current section in view. This feature improves navigation usability, especially in long single-page applications, by providing visual feedback to users as they scroll.

  • react-waypoint:

    react-waypoint allows you to define waypoints in your application that trigger actions when scrolled into view. This can include loading additional content, triggering animations, or changing styles, making it a flexible tool for scroll-based interactions.

Performance

  • react-in-viewport:

    react-in-viewport is lightweight and easy to implement, but it may not be as performant as other libraries when dealing with many elements due to its reliance on manual visibility checks. It is best suited for simpler applications where performance is not a critical concern.

  • react-intersection-observer:

    react-intersection-observer is highly performant as it leverages the native Intersection Observer API, which is designed to handle visibility checks efficiently without causing layout thrashing or excessive reflows, making it ideal for applications with many elements to observe.

  • react-scroll:

    react-scroll is optimized for smooth scrolling and provides a good user experience, but it may not handle performance as well when many scroll events are triggered simultaneously. It is best for applications where scroll navigation is a primary feature.

  • react-scrollspy:

    react-scrollspy is efficient in tracking scroll positions and updating navigation links, but it is dependent on the overall performance of the scroll event handling in the application. It works best in conjunction with other performance optimizations in the app.

  • react-waypoint:

    react-waypoint is designed to be lightweight and efficient, allowing you to trigger actions based on scroll position without significant performance overhead. It is suitable for applications that require dynamic interactions based on scrolling.

Ease of Use

  • react-in-viewport:

    react-in-viewport is very easy to use, with a simple API that allows developers to wrap components and manage visibility states with minimal setup. It is ideal for developers looking for quick implementation without extensive configuration.

  • react-intersection-observer:

    react-intersection-observer has a slightly steeper learning curve due to its reliance on the Intersection Observer API, but it provides a powerful and flexible solution once understood. It is suitable for developers who need advanced visibility management features.

  • react-scroll:

    react-scroll is straightforward to implement for creating smooth scroll effects and navigation. Its API is intuitive, making it easy for developers to get started with scroll-based navigation without much overhead.

  • react-scrollspy:

    react-scrollspy is easy to integrate into existing navigation systems, providing a simple way to enhance user experience with minimal configuration. Its API is user-friendly, making it accessible for developers of all skill levels.

  • react-waypoint:

    react-waypoint is also easy to use, with a clean API that allows developers to define waypoints and trigger actions with minimal code. It is suitable for developers looking to add scroll-triggered events quickly.

Use Cases

  • react-in-viewport:

    react-in-viewport is best used for scenarios where you need to manage the visibility of specific elements, such as lazy loading images or triggering animations when elements come into view. It is ideal for applications with limited visibility requirements.

  • react-intersection-observer:

    react-intersection-observer is perfect for complex applications that require monitoring multiple elements' visibility, such as infinite scrolling lists or triggering animations for various components as they enter the viewport.

  • react-scroll:

    react-scroll is ideal for single-page applications where smooth scrolling navigation is essential. It is commonly used for creating landing pages or documentation sites that require easy navigation between sections.

  • react-scrollspy:

    react-scrollspy is best suited for long single-page applications where you want to provide users with a clear indication of their current section. It enhances navigation usability and is often used in portfolio sites or documentation pages.

  • react-waypoint:

    react-waypoint is versatile and can be used in various scenarios, such as triggering animations, loading content, or changing styles based on scroll position. It is suitable for applications that require dynamic interactions based on user scrolling.

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

  • react-in-viewport:

    Choose react-in-viewport if you need a straightforward solution for detecting when elements enter or leave the viewport. It is simple to use and provides a clean API for managing visibility without the overhead of additional features.

  • react-intersection-observer:

    Select react-intersection-observer for a more robust and performant solution that leverages the Intersection Observer API. It is ideal for complex scenarios where you need to observe multiple elements and manage their visibility efficiently, especially in large applications.

  • react-scroll:

    Opt for react-scroll if your primary goal is to create smooth scrolling navigation within a single-page application. It is perfect for implementing scroll-to-anchor functionality and provides a simple way to manage scroll behavior with customizable options.

  • react-scrollspy:

    Use react-scrollspy when you want to highlight navigation links based on the current scroll position. This is particularly useful for creating a dynamic navigation menu that updates as users scroll through different sections of your page, enhancing usability and engagement.

  • react-waypoint:

    Choose react-waypoint if you need to trigger actions based on scroll position, such as animations or loading data when an element comes into view. It is versatile for implementing scroll-based events and can be combined with other libraries for enhanced functionality.

README for react-in-viewport

React In Viewport

npm gzip size downloads


Library to detect whether or not a component is in the viewport, using the Intersection Observer API.

This library also uses MutationObserver to detect the change of the target element.

npm install --save react-in-viewport

yarn add react-in-viewport

Examples

Demo

Why

A common use case is to load an image when a component is in the viewport (lazy load).

We have traditionally needed to monitor scroll position and calculate the viewport size, which can be a scroll performance bottleneck.

Modern browsers now provide a new API--Intersection Observer API--which can make implementating this effort much easier and performant.

Polyfill

For browsers not supporting the API, you will need to load a polyfill. Browser support table

require('intersection-observer');

Design

The core logic is written using React Hooks. We provide two interfaces: you can use handleViewport, a higher order component (HOC) for class based components, or use hooks directly, for functional components.

The HOC acts as a wrapper and attaches the intersection observer to your target component. The HOC will then pass down extra props, indicating viewport information and executing a callback function when the component enters and leaves the viewport.

Usages

Using Higher Order Component

When wrapping your component with handleViewport HOC, you will receive inViewport props indicating whether the component is in the viewport or not.

handleViewport HOC accepts three params: handleViewport(Component, Options, Config)

ParamsTypeDescription
ComponentReact ElementCallback function for when the component enters the viewport
OptionsObjectOptions you want to pass to Intersection Observer API
ConfigObjectConfigs for HOC (see below)

Supported config

ParamsTypeDefaultDescription
disconnectOnLeavebooleanfalseDisconnect intersection observer after leave

HOC Component Props

PropsTypeDefaultDescription
onEnterViewportfunctionCallback function for when the component enters the viewport
onLeaveViewportfunctionCallback function for when the component leaves the viewport

The HOC preserves onEnterViewport and onLeaveViewport props as a callback

Props passed down by HOC to your component

PropsTypeDefaultDescription
inViewportbooleanfalseWhether your component is in the viewport
forwardedRefReact refAssign this prop as a ref on your component
enterCountnumberNumbers of times your component has entered the viewport
leaveCountnumberNumber of times your component has left the viewport

NOTE: Need to add ref={this.props.forwardedRef} to your component

Example of a functional component

import handleViewport, { type InjectedViewportProps } from 'react-in-viewport';

const Block = (props: InjectedViewportProps<HTMLDivElement>) => {
  const { inViewport, forwardedRef } = props;
  const color = inViewport ? '#217ac0' : '#ff9800';
  const text = inViewport ? 'In viewport' : 'Not in viewport';
  return (
    <div className="viewport-block" ref={forwardedRef}>
      <h3>{ text }</h3>
      <div style={{ width: '400px', height: '300px', background: color }} />
    </div>
  );
};

const ViewportBlock = handleViewport(Block, /** options: {}, config: {} **/);

const Component = (props) => (
  <div>
    <div style={{ height: '100vh' }}>
      <h2>Scroll down to make component in viewport</h2>
    </div>
    <ViewportBlock onEnterViewport={() => console.log('enter')} onLeaveViewport={() => console.log('leave')} />
  </div>
))

Example for enter/leave counts

  • If you need to know how many times the component has entered the viewport, use the prop enterCount.
  • If you need to know how many times the component has left the viewport, use the prop leaveCount.
import React, { Component } from 'react';
import handleViewport from 'react-in-viewport';

class MySectionBlock extends Component {
  getStyle() {
    const { inViewport, enterCount } = this.props;
    //Fade in only the first time we enter the viewport
    if (inViewport && enterCount === 1) {
      return { WebkitTransition: 'opacity 0.75s ease-in-out' };
    } else if (!inViewport && enterCount < 1) {
      return { WebkitTransition: 'none', opacity: '0' };
    } else {
      return {};
    }
  }

  render() {
    const { enterCount, leaveCount, forwardedRef } = this.props;
    return (
      <section ref={forwardedRef}>
        <div className="content" style={this.getStyle()}>
          <h1>Hello</h1>
          <p>{`Enter viewport: ${enterCount} times`}</p>
          <p>{`Leave viewport: ${leaveCount} times`}</p>
        </div>
      </section>
    );
  }
}
const MySection = handleViewport(MySectionBlock, { rootMargin: '-1.0px' });

export default MySection;

Using Hooks

Alternatively, you can also directly using useInViewport hook which takes similar configuration as HOC.

import React, { useRef } from 'react';
import { useInViewport } from 'react-in-viewport';

const MySectionBlock = () => {
  const myRef = useRef(null);
  const {
    inViewport,
    enterCount,
    leaveCount,
  } = useInViewport(
    myRef,
    options,
    config = { disconnectOnLeave: false },
    props
  );

  return (
    <section ref={myRef}>
      <div className="content" style={this.getStyle()}>
        <h1>Hello</h1>
        <p>{`Enter viewport: ${enterCount} times`}</p>
        <p>{`Leave viewport: ${leaveCount} times`}</p>
      </div>
    </section>
  );
};

Who is using this component