Skip to content

useSmartPolling – Visibility-Aware Data Polling Hook for React

Overview

Polls an async function on an interval. Pauses when the tab is hidden, resumes when visible, and skips re-renders when data hasn’t changed (shallow JSON comparison). Prevents overlapping fetches.

The initial fetch always fires immediately, regardless of the enabled flag.

Usage

import { useSmartPolling } from "react-visibility-hooks";
function Dashboard() {
const { data, isLoading, isError, error, refetch } = useSmartPolling(
() => fetch("/api/stats").then((r) => r.json()),
{ interval: 3000 },
);
if (isLoading) return <p>Loading…</p>;
if (isError) return <p>Error: {error?.message}</p>;
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
<button onClick={refetch}>Refresh now</button>
</div>
);
}

Conditional polling

const { data } = useSmartPolling(fetchData, {
interval: 5000,
enabled: user.isLoggedIn, // only poll when logged in
});

API

Parameters

ParameterTypeDescription
fetchFn() => Promise<T>Async function returning data
optionsSmartPollingOptions?Optional configuration

Options (SmartPollingOptions)

OptionTypeDefaultDescription
intervalnumber5000Polling interval in ms
enabledbooleantrueEnable / disable polling. Initial fetch always fires.

Returns (SmartPollingResult<T>)

PropertyTypeDescription
dataT | undefinedThe latest fetched data
isLoadingbooleantrue until the first fetch completes
isErrorbooleantrue if the last fetch threw
errorError | undefinedThe error object, if any
refetch() => Promise<void>Manually trigger a fetch