GithubHelp home page GithubHelp logo

chenshuy1 / use-intersection-observer Goto Github PK

View Code? Open in Web Editor NEW

This project forked from asyarb/use-intersection-observer

0.0 1.0 0.0 656 KB

Small React hook wrapper around the IntersectionObserver API.

License: MIT License

JavaScript 0.78% HTML 5.66% TypeScript 93.57%

use-intersection-observer's Introduction

use-intersection-observer

NPM npm bundle size

React implementation of the intersection Observer Interface to tell you when an element is visible in the viewport.

Features

  • Hooks API - Provide a ref!
  • Alternative Native-esque API - Pass an HTMLElement and an optional function to handle IntersectionObserver callbacks.
  • Isolated - Intersections will not cause other observed elements to re-render.
  • Typed - Written with TypeScript!

Installation

Run the following:

# Yarn
yarn add @asyarb/use-intersection-observer

# NPM
npm i @asyarb/use-intersection-observer --save

Usage

Provide a ref from useRef

To observe the visibility of a component, pass a ref of that component to useIntersectionObserver:

const Example = () => {
  const ref = useRef()

  // Get the visibility boolean directly from the hook:
  const inView = useIntersectionObserver({
    ref,
    options: {
      threshold: 0.25,
      triggerOnce: true,
    },
  })

  useEffect(() => {
    if (inView) {
      // => Perform any side effect with it!
    }
  }, [inView])

  return <div ref={ref}>Some content...</div>
}

inView will be updated whenever the observed element passes the specified threshold.

Optionally, you can pass a callback function as the third parameter to perform any side effect on intersection. This function receives list of IntersectionObserver entries (IntersectionObserverEntry[]) array as an argument.

const Example = () => {
  const ref = useRef()

  // Pass an optional callback to perform side effects instead:
  useIntersectionObserver({
    ref,
    callback: entries => entries.forEach(e => console.log(e)),
  })

  return <div ref={ref}>Some content...</div>
}

Provide a DOM element

useIntersectionObserver can alternatively take an Element such as the return value from document.querySelector().

const element = document.querySelector('.someClass')

const Example = () => {
  // Pass an HTMLElement directly:
  const inView = useIntersectionObserver({ element })

  return <div>Some content...</div>
}

Just like the ref examples, you can optionally provide a callback function.

API

Argument Description
ref React ref to observe.
element Alternative HTML Element to observe. If both element and ref are defined, ref is prioritized.
options IntersectionObserverOptions object with an additional triggerOnce argument.
callback Optional callback to fire on intersection. Receives the array of IntersectionObserverEntry objects for the provided ref or element

Why use this over react-intersection-observer

This package aims to prioritize performance for different use-cases.

react-intersection-observer utilizes a single IntersectionObserver instance to observe all elements that use the useInView hook. By doing so, browsers can batch IntersectionObserver callbacks together.

Conversely, this will cause any observered element's intersection to cause cause all observered components to re-render, not just itself. Even when using the triggerOnce flag, components will still re-render post-intersection due to callbacks still firing from a unified instance.

This package creates an IntersectionObserver instance for each unique component that consumes the hook. This prevents the aforementioned issues at the cost of additional overhead of creating an instance per element and losing batched callbacks. This is remedied a bit by the triggerOnce flag as we can disconnect instances entirely after intersection.

Summary

If re-rendering your observered components are your most expensive operation, or you just can't have re-rendering from other elements coming into view (e.g. animations), consider using this package.

If callbacks are your most expensive operation during intersection, react-intersection-observer may be a better fit.

As always, try both and see what works best for your application.

License

MIT.

use-intersection-observer's People

Contributors

asyarb avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.