HooksuseIntersectionObserver

useIntersectionObserver

A React hook that uses the IntersectionObserver API to detect when an element is in view.

Installation

npm install @madeinhaus/hooks

Import

import { useIntersectionObserver } from '@madeinhaus/hooks';

Parameters

  • options (IntersectionObserverOptions, optional): An optional object that can contain the following properties:
    • once (boolean, default: true): If false, the observer will continue observing the element after it first becomes visible. If true (default), the observer will unobserve the element after it first becomes visible.
    • root (Element | Document, optional): The element that is used as the viewport for checking visibility of the target. Defaults to the browser viewport if not specified or if null.
    • rootMargin (string, optional): Margin around the root element. Can have values similar to the CSS margin property. Defaults to all zeros if not specified or if null.
    • threshold (number | number[], optional): Either a single number or an array of numbers which indicate at what percentage of the target’s visibility the observer’s callback should be executed. Defaults to 0 if not specified or if null.

Returns

  • inView (boolean): A boolean indicating if the component is in view.
  • ref (function): A callback ref that you pass to the element’s ref prop.
  • elRef (Ref): A ref object that you can use to access the element if needed.

Usage

import { useIntersectionObserver } from '@madeinhaus/hooks';
 
function MyComponent() {
  const [inView, ref] = useIntersectionObserver({
    once: false,
    rootMargin: '0px 0px -100px 0px',
    threshold: 0.5,
  });
 
  return <div ref={ref}>{inView ? 'In view' : 'Not in view'}</div>;
}

In this example, we import the useIntersectionObserver hook from the @madeinhaus/hooks package and use it to detect when a div element is in view.