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

react-hook-inview

v4.5.0

Published

React Hook for detecting when an element is in the viewport

Downloads

37,194

Readme

react-hook-inview

npm version

Detect if an element is in the viewport using a React Hook. Utilizes the Intersection Observer API, so check for compatibility.

Install

npm install react-hook-inview

Optional: Install a polyfill for browsers that don't support IntersectionObserver yet (i.e. Safari 12).

useInView

The hook in its most basic form returns a ref and a boolean.

const [ref, inView] = useInView()

That's all you need to get started, but it does a lot more.

Example

In this example, the boolean is used to toggle some text on and off when the element is fully in the viewport.

import React from 'react'
import { useInView } from 'react-hook-inview'

const Component = () => {
  const [ref, isVisible] = useInView({
    threshold: 1,
  })

  return <div ref={ref}>{isVisible ? 'Hello World!' : ''}</div>
}

API

The hook returns a tuple with four items:

  • A ref callback, used to set observer on an element.
  • A boolean when the element is in the viewport.
  • The IntersectionObserverEntry
  • The IntersectionObserver itself
const [ref, inView, entry, observer] = useInView(options, [...state])

Options

These are the default options.

{
  root?: RefObject<Element> | null, // Optional, must be a parent of your ref
  rootMargin?: string,              // '0px' or '0px 0px 0px 0px', also accepts '%' unit
  threshold?: number | number[],    // 0.5 or [0, 0.5, 1]
  unobserveOnEnter?: boolean,       // Set 'true' to run only once
  onEnter?: (entry?, observer?) => void, // See below
  onLeave?: (entry?, observer?) => void, // See below
  target?: RefObject<Element> | null,    // *DEPRECATED* Supply your own ref object
  defaultInView?: boolean, // false
}

NOTE If you're updating from < version 4.0.0., you might have noticed an API changed. The target option has been deprecated, but still works the same way.

onEnter & onLeave callbacks

:warning: These options are deprecated, and support may be removed in a future release. To access the intersection observer callback, use the useInViewEffect hook instead.

onEnter and onLeave recieve a callback function that returns an IntersectionObserverEntry and the IntersectionObserver itself. The two arguments are entirely optional.

function onEnter(entry, observer) {
  // entry.boundingClientRect
  // entry.intersectionRatio
  // entry.intersectionRect
  // entry.isIntersecting
  // entry.rootBounds
  // entry.target
  // entry.time
}

NOTE: If you supply an array with multiple values to threshold, onEnter will be called each time the element intersects with the top and bottom of the viewport. onLeave will on trigger once the element has left the viewport at the first threshold specified.

Accessing external state in callbacks

For performance reasons, the hook is only triggered once on mount. However, this means you can't access updated state in the onEnter/onLeave callbacks. An optional second argument will retrigger the hook to mitigate this.

// Some other state
const [state, setState] = useState(false)

const [ref, inView] = useInView(
  {
    onEnter: () => console.log(state),
  },
  [state], // <- Will update callback
)

This will remount the intersection observer, and may have unintended side effects. Use this feature with caution.

useInViewEffect

An alternate hook that allows you to just supply the intersection observer callback. This approach is gives you a little more flexibilty than using the callbacks in the original hook as it doesn't obfuscate the Intersection Observer API as much.

const ref = useInViewEffect(callback, options, [...state])

Example

import React, { useState } from 'react'
import { useInViewEffect } from 'react-hook-inview'

const Component = () => {
  const [isVisible, setIsVisible] = useState(false)

  const ref = useInViewEffect(
    ([entry], observer) => {
      if (entry.isIntersecting) {
        observer.unobserve(entry.target)
      }
      setIsVisible(entry.isIntersecting)
    },
    { threshold: 0.5 },
  )

  return <div ref={ref}>{isVisible ? 'Hello World!' : ''}</div>
}

Keep in mind that the first argument will return an array.

Options

The useInViewEffect hook has more limited options that mirror the default API.

{
  root?: RefObject<Element> | null, // Optional, must be a parent of your ref
  rootMargin?: string,              // '0px' or '0px 0px 0px 0px', also accepts '%' unit
  threshold?: number | number[],    // 0.5 or [0, 0.5, 1]
}

License

MIT