Skip to content

useImpressionRef ​

useImpressionRef is a React hook that measures the time a specific DOM element is visible on the screen and executes callbacks when the element enters or exits the viewport. It uses IntersectionObserver and the Visibility API to track the element's visibility.

Interface ​

ts
function useImpressionRef<Element extends HTMLElement>(
  options: UseImpressionRefOptions
): (element: Element | null) => void;

Parameters ​

  • optionsrequired · UseImpressionRefOptions

    Options for tracking the element's visibility.

    • options.onImpressionStart() => void

      Callback function executed when the element enters the view

    • options.onImpressionEnd() => void

      Callback function executed when the element exits the view

    • options.timeThresholdnumber · 0

      Minimum time the element must be visible (in milliseconds)

    • options.areaThresholdnumber · 0

      Minimum ratio of the element that must be visible (0 to 1)

    • options.rootMarginstring

      Margin to adjust the detection area

Return Value ​

  • (element: Element | null) => void

    A function to set the element. Attach this function to the ref attribute, and the callbacks will be executed whenever the element's visibility changes.

Example ​

tsx
import { useImpressionRef } from 'react-simplikit';

function Component() {
  const ref = useImpressionRef<HTMLDivElement>({
    onImpressionStart: () => console.log('Element entered view'),
    onImpressionEnd: () => console.log('Element exited view'),
    timeThreshold: 1000,
    areaThreshold: 0.5,
  });

  return <div ref={ref}>Track my visibility!</div>;
}

Released under the MIT License.