Loading...
Please waitLoading...
Please waitMeasure how long a user actually views a component, using visibility tracking and timers instead of simple impressions.
pnpm dlx uselab@latest add use-view-time
import * as React from "react"
import { useViewTime } from "@/hooks/use-view-time"
export function AnalyticsRow() {
const ref = React.useRef<HTMLDivElement | null>(null)
const { secondsViewed } = useViewTime(ref, { threshold: 0.5 })
return <div ref={ref}>Viewed for {secondsViewed}s</div>
}useViewTime(ref, options?)Tracks how long the referenced element is considered visible in the viewport, updating a running total in seconds.
| Name | Type | Description | Optional | Default |
|---|---|---|---|---|
ref | React.RefObject<HTMLElement | null> | Ref pointing to the DOM node you want to track. | No | — |
options | UseViewTimeOptions | Configuration object for visibility thresholds. | Yes | {} |
threshold | number | Intersection ratio required before a period counts as “viewed” (0–1). | Yes | 0.5 |
The hook returns an object { secondsViewed }:
| Name | Type | Description |
|---|---|---|
secondsViewed | number | Total whole seconds the element has been considered visible. |
interface UseViewTimeOptions {
threshold?: number
}
interface UseViewTimeResult {
secondsViewed: number
}IntersectionObserver to detect when the element meets the configured threshold (e.g. 50% visible).visibilitychange).secondsViewed.ref; re-mounting a component resets its timer.useViewTime with your own event pipeline to send summarized counts to your backend.Timers only advance when a row is at least 40% visible and the document tab is active.