Real Time Polling in React Query 2025
Real Time Polling in React Query 2025
React Query (TanStack Query) allows you to set up real-time polling of APIs using the refetchInterval
option. This makes it easier to keep your UI data up-to-date without requiring manual user action.
📌 Step-by-step Explanation:
- Polling: Re-fetching data automatically after a specific interval (e.g., every 5 seconds).
- When to use: For real-time dashboards, live feeds, or constantly updating data.
- How: Use
refetchInterval
inside the useQuery
hook.
✅ Code Example:
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchPosts = async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
return res.data;
};
function PollingComponent() {
const { data, isLoading, isError } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
refetchInterval: 5000, // Poll every 5 seconds
});
if (isLoading) return Loading...
;
if (isError) return Error fetching data
;
return (
{data.map(post => (
{post.title}
{post.body}
))}
);
}
export default PollingComponent;
📚 Notes:
- Polling is useful for time-sensitive data like messages, stocks, or status updates.
- Use
refetchIntervalInBackground: true
if you want polling even when the window is not focused.
- Turn off polling conditionally using
enabled
or refetchInterval: false
.