useImpressionRef
useImpressionRef
is a custom 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. This hook uses IntersectionObserver
and the Visibility API
to track the element's visibility.
Interface
ts
function useImpressionRef(
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.rootMarginrequired · string
Margin to adjust the detection area
- options.onImpressionStart() => void
Return Value
- (element: Element | null) => void
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>;
}