npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@asyarb/use-intersection-observer

v2.0.2

Published

An easy to use React hook wrapper around the IntersectionObserver API.

Downloads

1,278

Readme

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.

Demo: TODO Code Sandbox

Features

  • Hooks API - Just provide a ref!
  • Alternative Native-esque API - Pass an HTMLElement and an optional function to handle IntersectionObserver callbacks.
  • Performant - 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 the IntersectionObserver entry (IntersectionObserverEntry) object as an argument.

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

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

  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 additional triggerOnce flag. | | callback | Optional callback to fire on intersection. Receives the IntersectionObserverEntry object 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.