usePoll
Poll APIs at regular intervals with pause/resume control. Perfect for real-time data updates and monitoring.
Live Demo
Try different polling scenarios: auto-start, custom intervals, and manual control with pause/resume.
💬 Auto-Polling Quotes
Polls every 5 seconds, starts automatically
🟢 Polling Active
⏰ Custom Interval Polling
Adjust polling interval dynamically
⚪ Not Polling
Click "Start Polling" to begin
🎲 Manual Control Polling
Start/stop polling and manual refetch (polls every 2 seconds)
⚪ Not Polling
Start polling or click manual refetch
💡 Features Demonstrated:
- Automatic polling with configurable intervals
- Start/stop (pause/resume) polling dynamically
- Manual refetch without affecting polling state
- Custom interval configuration
- Immediate execution on start
- Loading and error states
Code Examples
Basic Usage
import { usePoll } from "@uiblock/hooks";
const fetchStatus = async () => {
const response = await fetch('/api/status');
return response.json();
};
export default function StatusMonitor() {
const { data, loading, error, isPolling, start, stop } = usePoll(
fetchStatus,
{ interval: 5000 } // Poll every 5 seconds
);
return (
<div>
<button onClick={isPolling ? stop : start}>
{isPolling ? 'Pause' : 'Resume'}
</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
{data && <div>Status: {data.status}</div>}
</div>
);
}Manual Start (No Auto-Start)
import { usePoll } from "@uiblock/hooks";
export default function DataMonitor() {
const { data, isPolling, start, stop } = usePoll(
async () => {
const res = await fetch('/api/data');
return res.json();
},
{
interval: 3000,
enabled: false, // Don't start automatically
immediate: false // Don't fetch immediately when started
}
);
return (
<div>
<button onClick={start} disabled={isPolling}>
Start Monitoring
</button>
<button onClick={stop} disabled={!isPolling}>
Stop Monitoring
</button>
<div>Status: {isPolling ? 'Active' : 'Inactive'}</div>
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}With Callbacks
import { usePoll } from "@uiblock/hooks";
import { useState } from "react";
export default function NotificationPoller() {
const [notifications, setNotifications] = useState([]);
const { isPolling, start, stop } = usePoll(
async () => {
const res = await fetch('/api/notifications');
return res.json();
},
{
interval: 10000, // Poll every 10 seconds
onSuccess: (data) => {
if (data.new) {
// Show notification
new Notification('New update!', {
body: data.message
});
}
setNotifications(data.items);
},
onError: (error) => {
console.error('Polling failed:', error);
}
}
);
return (
<div>
<button onClick={isPolling ? stop : start}>
{isPolling ? 'Stop' : 'Start'} Notifications
</button>
<ul>
{notifications.map(n => (
<li key={n.id}>{n.message}</li>
))}
</ul>
</div>
);
}Manual Refetch
import { usePoll } from "@uiblock/hooks";
export default function Dashboard() {
const {
data,
loading,
isPolling,
start,
stop,
refetch
} = usePoll(
async () => {
const res = await fetch('/api/dashboard');
return res.json();
},
{ interval: 30000 } // Poll every 30 seconds
);
return (
<div>
<div>
<button onClick={isPolling ? stop : start}>
{isPolling ? 'Pause' : 'Resume'} Auto-Refresh
</button>
<button onClick={refetch} disabled={loading}>
Refresh Now
</button>
</div>
{loading && <p>Refreshing...</p>}
{data && (
<div>
<h2>Dashboard Data</h2>
<p>Last updated: {new Date().toLocaleTimeString()}</p>
{/* Render dashboard */}
</div>
)}
</div>
);
}Dynamic Interval
import { usePoll } from "@uiblock/hooks";
import { useState } from "react";
export default function ConfigurablePoller() {
const [interval, setInterval] = useState(5000);
const { data, isPolling, start, stop } = usePoll(
async () => {
const res = await fetch('/api/data');
return res.json();
},
{
interval,
enabled: false
}
);
const handleIntervalChange = (newInterval: number) => {
const wasPolling = isPolling;
if (wasPolling) stop();
setInterval(newInterval);
if (wasPolling) {
// Restart with new interval
setTimeout(start, 100);
}
};
return (
<div>
<select
value={interval}
onChange={(e) => handleIntervalChange(Number(e.target.value))}
>
<option value={1000}>1 second</option>
<option value={5000}>5 seconds</option>
<option value={10000}>10 seconds</option>
<option value={30000}>30 seconds</option>
</select>
<button onClick={isPolling ? stop : start}>
{isPolling ? 'Stop' : 'Start'}
</button>
{data && <div>{JSON.stringify(data)}</div>}
</div>
);
}API Reference
Parameters
fetchFunction: () => Promise<T>The async function to poll
options?: UsePollOptions<T>Optional configuration object
interval: Polling interval in milliseconds (default: 5000)enabled: Start polling automatically (default: true)immediate: Fetch immediately when polling starts (default: true)onSuccess: Callback when fetch succeedsonError: Callback when fetch fails
Return Value
data: T | nullThe latest fetched data
error: Error | nullError object if fetch failed
loading: booleanTrue while fetching data
isPolling: booleanTrue if polling is active
start: () => voidStart/resume polling
stop: () => voidStop/pause polling
refetch: () => Promise<void>Manually trigger a fetch without affecting polling state
💡 Use Cases
- Real-time status monitoring
- Live data dashboards
- Notification polling
- Server health checks
- Stock price updates
- Chat message polling
- Job status tracking