usePolling
Poll an async function on an interval.
Import
TypeScript
import { usePolling } from '@/hooks';API
Signature
usePolling(fn, options?) → { data, loading, error, refetch }
When to use
Use usePolling instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Client-side. Prefer RSC for first-paint server data.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · usePollingEditor
function LiveStatus() { const { data, loading } = usePolling( async () => (await fetch('/api/users')).json(), { interval: 5000, enabled: true }, ); return <pre>{loading ? '…' : JSON.stringify(data, null, 2)}</pre>; }
Preview
Implementation source
Full library source for usePolling — copy into your project when you are not installing a package yet.
hooks/async/usePolling.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { useInterval } from '../timer/useInterval';
import { useIsMounted } from '../utility/useIsMounted';
import { useLatest } from '../utility/useLatest';
export interface UsePollingOptions<T> {
interval?: number;
/** @default true */
enabled?: boolean;
immediate?: boolean;
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
}
/** Polls an async function on an interval until disabled. */
export function usePolling<T>(
fn: () => Promise<T>,
options: UsePollingOptions<T> = {},
) {
const {
interval = 5000,
enabled = true,
immediate = true,
onSuccess,
onError,
} = options;
const isMounted = useIsMounted();
const fnRef = useLatest(fn);
const [data, setData] = useState<T | undefined>(undefined);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(false);
const inFlight = useRef(false);
const tick = useCallback(async () => {
if (inFlight.current) return;
inFlight.current = true;
setLoading(true);
try {
const result = await fnRef.current();
if (!isMounted()) return;
setData(result);
setError(null);
onSuccess?.(result);
} catch (e) {
if (!isMounted()) return;
const err = e instanceof Error ? e : new Error(String(e));
setError(err);
onError?.(err);
} finally {
inFlight.current = false;
if (isMounted()) setLoading(false);
}
}, [fnRef, isMounted, onSuccess, onError]);
useInterval(tick, enabled ? interval : null, {
immediate,
autoStart: enabled,
});
useEffect(() => {
if (!enabled) return;
// interval hook handles scheduling
}, [enabled]);
return { data, error, loading, refetch: tick };
}
Copy-paste example
usePolling.example.tsx
'use client';
import { usePolling } from '@/hooks';
export function LiveStatus() {
const { data, loading } = usePolling(
async () => (await fetch('/api/users')).json(),
{ interval: 5000, enabled: true },
);
return <pre>{loading ? '…' : JSON.stringify(data, null, 2)}</pre>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Abort in-flight work when the URL changes. Prefer null URL / enabled:false to skip.
- Source of truth: open
hooks/async/usePolling.tsfor implementation details