Skip to content

useIntersectionObserver ​

Hook that gives you intersection observer state

browser
test coverage
Last changed: yesterday

TIP

This hook uses IntersectionObserver browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation ​

Library
CLI
Manual
typescript
import { useIntersectionObserver } from '@siberiacancode/reactuse';

Usage ​

typescript
const { ref, entry, inView } = useIntersectionObserver();
// or
const { entry, inView } = useIntersectionObserver(ref);

Demo ​

Api ​

Parameters

NameTypeDefaultNote
targetHookTarget-The target element to detect intersection
options.enabled?booleantrueThe IntersectionObserver options
options.onChange?((entries: IntersectionObserverEntry[], observer: IntersectionObserver) => void) | undefined-The callback to execute when intersection is detected
options.root?HookTarget-The root element to observe

Returns

UseIntersectionObserverReturn

Parameters

NameTypeDefaultNote
options.enabled?booleantrueThe IntersectionObserver options
options.onChange?((entries: IntersectionObserverEntry[], observer: IntersectionObserver) => void) | undefined-The callback to execute when intersection is detected
options.root?HookTarget-The root element to observe

Returns

UseIntersectionObserverReturn & { ref: StateRef<Target> }

Type declaration ​

typescript
import type { HookTarget } from '@/utils/helpers';

import type { StateRef } from '../useRefState/useRefState';

export interface UseIntersectionObserverOptions extends Omit<IntersectionObserverInit, 'root'> {
  enabled?: boolean;
  root?: HookTarget;
  onChange?: (entry: IntersectionObserverEntry) => void;
}

export interface UseIntersectionObserverReturn {
  entry?: IntersectionObserverEntry;
  inView: boolean;
}

export interface UseIntersectionObserver {
  <Target extends Element>(
    options?: UseIntersectionObserverOptions,
    target?: never
  ): UseIntersectionObserverReturn & { ref: StateRef<Target> };

  (target: HookTarget, options?: UseIntersectionObserverOptions): UseIntersectionObserverReturn;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin

Released under the MIT License.