one-hook
Size
0.67 kb
View source

useIntersectionObserver

The IntersectionObserver API, reactified, simplified and optimized.

Features

  • Instance Reuse: Optimizes performance by reusing IntersectionObserver instances based on options.
  • Convenient Unwrapping: Automatically unwraps the entries parameter, allowing direct access to each entry in the callback.
  • Manual Observation Control: Allows manual control over observation using the observe and unobserve functions.

Installation

npm install @1hook/use-intersection-observer

Usage

import {  } from '@1hook/use-intersection-observer'

Observe an element's intersection with the viewport:

function () {
  const {  } = (() => {
    .({ : . })
  })

  return < ={} />
}

Customize the intersection observer:

function () {
  const {  } = (
    () => .({ : . }),
    { : '100px' },
  )

  return < ={} />
}

Stop observing the target after the first intersection:

function () {
  const { ,  } = (() => {
    if (!.) return
    .('Intersected!')
    ()
  })

  return < ={} />
}

API Reference

UseIntersectionObserverOptions

Options for the useIntersectionObserver hook.

PropTypeDefault
autoObserve?
boolean
true
threshold?
number | number[]
-
rootMargin?
string
-
root?
Element | Document | null
-

UseIntersectionObserverReturn

Return value for the useIntersectionObserver hook.

PropTypeDefault
target
Element | null
-
ref
Function
-
unobserve
() => void
-
observe
() => void
-

On this page