Skip to main content

Function: useImpression()

useImpression<T>(onImpression, options?): (element) => void

Defined in: use-impression.ts:120

Calls onImpression once an element has been at least threshold visible for at least minDurationMs, which is what analytics, "mark as read" and ad-view tracking usually mean by "seen".

It differs from useIntersectionObserver, which reports visibility as state but has no notion of dwell time, and the hook itself never re-renders your component.

  • Usage: attach the returned ref to any element. It is a callback ref, so it also works when the element mounts later, is rendered conditionally, or is swapped for another one.
  • Dwell time: the timer starts when the element becomes visible enough and is reset if it drops below threshold before minDurationMs passes.
  • Hidden tabs: the timer is paused while the document is hidden, so time in a background tab does not count, and it resumes when the tab is visible again.
  • Once or repeated: by default one impression is reported per element. With once: false, the element is reported again after it leaves the viewport and stays visible for minDurationMs again.
  • Stable: the latest onImpression is always called, so passing an inline function never resets the timer or re-observes. Changing root, rootMargin, threshold, minDurationMs, once or enabled does.
  • Pause: enabled: false disconnects the observer and clears the timer.
  • SSR-safe: nothing runs on the server, and it does nothing where IntersectionObserver is unavailable.
  • Cleanup: the observer, the timer and the visibility listener are removed on unmount, when the element changes and when an option changes. The callback is never called after unmount.

Type Parameters​

T​

T extends Element = HTMLElement

The type of element being observed. Defaults to HTMLElement.

Parameters​

onImpression​

(entry) => void

Called with the latest IntersectionObserverEntry when an impression is reported.

options?​

UseImpressionOptions

Optional threshold, minDurationMs, once, root, rootMargin and enabled settings. See UseImpressionOptions.

Returns​

A callback ref to attach to the element you want to track.

(element) => void

Examples​

// Report a view after the card was at least half visible for one second
const ref = useImpression<HTMLDivElement>(() => {
analytics.track("card_viewed", { id });
});

return <div ref={ref}>{children}</div>;
// Mark a message as read after 2 seconds with 80% of it on screen
const ref = useImpression<HTMLLIElement>(() => markAsRead(message.id), {
threshold: 0.8,
minDurationMs: 2000,
enabled: !message.read,
});
// Count every time an ad is seen again, inside a scrollable feed
const ref = useImpression<HTMLDivElement>(
(entry) => trackAdView(adId, entry.intersectionRatio),
{ once: false, root: feedRef.current }
);

For a live, editable example, see the useImpression docs page.

See​