Polling and Refetching Strategies
You'll learn how to keep your Apollo Client data fresh with automatic polling, manual refetches, and cache-first vs network-only fetch policies.
When working with GraphQL data through Apollo Client, you often need strategies to keep information current. Should you automatically check for updates? Fetch from the network every time? Or trust your cache?
Core Refetching Strategies
Polling Intervals
Apollo's useQuery supports automatic polling—repeatedly fetching data at set intervals. Think of it like checking your mailbox every 5 minutes instead of waiting for a notification:
const { data } = useQuery(GET_MESSAGES, {
pollInterval: 5000 // Refetch every 5 seconds
});
Set pollInterval: 0 to stop polling. Polling pauses automatically when components unmount or the browser tab is hidden.
Manual Refetch Triggers
Sometimes you want explicit control. The refetch function lets you request fresh data on-demand:
const { data, refetch } = useQuery(GET_PROFILE);
// Later, in an event handler:
<button onClick={() => refetch()}>Refresh Profile</button>
This respects your current fetch policy and re-runs the query.
Fetch Policies: Cache vs Network
Apollo offers different policies controlling where data comes from:
cache-first(default): Use cached data if available, only hit network if missing. Fast but potentially stale.network-only: Always fetch from server, bypass cache. Guarantees freshness but slower.cache-and-network: Return cached data immediately, then fetch fresh data in background.
const { data } = useQuery(GET_STATS, {
fetchPolicy: 'network-only' // Always fresh, ignore cache
});
Choose cache-first for mostly-static data, network-only for critical real-time information, and polling for dashboard-style updates.
Key Takeaway: Apollo Client lets you balance freshness and performance through polling intervals for automatic updates, manual refetch() triggers for user-initiated refreshes, and fetch policies that control whether to prioritize cache speed or network accuracy.