Skip to content

useIntersectionObserver

Category
Export Size
674 B
Last Changed
5 days ago

Detects changes to a target element's visibility

Demo

Usage

tsx
import { 
useIntersectionObserver
} from '@reause/core'
import {
useRef
,
useState
} from 'react'
const
target
=
useRef
<HTMLDivElement | null>(null)
const [
targetIsVisible
,
setIsVisible
] =
useState
(false)
const {
stop
} =
useIntersectionObserver
(
target
,
([
entry
]) => {
setIsVisible
(
entry
?.
isIntersecting
|| false)
}, )

Controls and cleanup

useIntersectionObserver returns controls for the underlying observer:

StateTypeDescription
isSupportedbooleanWhether the IntersectionObserver API is available.
isActivebooleanWhether the observer is currently running. Turns false after pause() or stop().
pause() => voidPause observing and set isActive to false.
resume() => voidResume observing.
stop() => voidStop observing permanently.

The observer is disconnected automatically on unmount, so in most cases you don't need to call stop yourself. Call stop() to disconnect the observer earlier, for example once the element has become visible:

ts
const { 
stop
} =
useIntersectionObserver
(
target, ([
entry
]) => {
if (
entry
?.
isIntersecting
) {
// react to the element becoming visible once, then stop observing
stop
()
} }, )

IntersectionObserver MDN

Type Declarations

ts
export interface UseIntersectionObserverOptions {
    window?: Window | null;
    immediate?: boolean;
    root?: ElementTarget | RefObject<Document | null>;
    rootMargin?: string;
    threshold?: number | number[];
}

export interface UseIntersectionObserverReturn {
    isSupported: boolean;
    isActive: boolean;
    pause: () => void;
    resume: () => void;
    stop: () => void;
}

export type ElementTarget<T extends TargetElement = TargetElement> = RefObject<T | null>

export type ElementTargetOrArray<T extends TargetElement = TargetElement> = ElementTarget<T> | ElementTarget<T>[]

export function useIntersectionObserver(target: ElementTargetOrArray, callback: IntersectionObserverCallback, options?: UseIntersectionObserverOptions): UseIntersectionObserverReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
c82b0 - fix(core): resolve useIntersectionObserver audit findings (#584)
c75a2 - fix(core): resolve useElementVisibility audit findings (#552)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8