Interval Refetching

Purpose and Scope

Interval refetching is the polling pattern in SWR: a component reads from the cache immediately when possible, then asks SWR to fetch the same resource again on a schedule so the view keeps moving toward fresh data. This recipe is useful for dashboards, activity feeds, job status pages, queue monitors, or any screen where the user should not need to press refresh to see new server state. The root README frames SWR as a React Hooks library for data fetching and explicitly lists polling alongside focus revalidation, network recovery revalidation, pagination, SSR, optimistic UI, TypeScript, Suspense, and React Native support. Sources: README.md

The refetch-interval example’s reader-facing goal is intentionally narrow: show how to make SWR fetch an API again automatically in an interval to keep data up to date. That fits the broader SWR model from the README: SWR first returns cached data, then revalidates, and finally updates the component with fresh data. An interval does not replace that cache-first behavior. Instead, it adds another revalidation trigger after the initial render, giving the component a stream of updates without changing the fetcher contract. Sources: README.md

Relevant Source Files

  • README.md — Establishes SWR as a React Hooks data-fetching library, explains stale-while-revalidate, shows the minimal useSWR(key, fetcher) shape, and names polling as a built-in capability.
  • e2e/site/README.md — Documents the local Next.js development flow, including npm run dev, yarn dev, pnpm dev, browser access at http://localhost:3000, and the role of pages/api as API routes.

Core Primitives

A polling example still uses the same primitives as the quick-start example. The key identifies the resource and is commonly a URL such as /api/user. The fetcher is any asynchronous function that accepts the key and returns data. The hook returns state such as data, error, and isLoading, allowing the component to render loading, failure, and success states without manually coordinating promises and React state. Interval refetching adds an option to the hook call, but it does not require a different component architecture. Sources: README.md

The important mental model is that interval refetching schedules repeated revalidation of the same cache entry. When the interval fires, SWR calls the fetcher for the same key, compares the result through its normal update path, and rerenders consumers that observe changed data. The UI can remain responsive because it continues to show the previous cached value while the next request is in flight. That is the practical meaning of the README’s statement that components receive a stream of data updates constantly and automatically. Sources: README.md

A minimal polling component can be read as three layers: fetch, subscribe, and render. The fetcher describes how to retrieve the resource. useSWR subscribes the component to a cache key and handles request lifecycle state. The interval option tells SWR how often to revisit the resource after the initial read. Keep the fetcher reusable and side-effect-light; the interval may call it many times while the component remains mounted, so it should represent an idempotent read operation rather than an irreversible write.

import useSWR from 'swr'
 
const fetcher = url => fetch(url).then(res => res.json())
 
export default function StatusPanel() {
  const { data, error, isLoading } = useSWR('/api/status', fetcher, {
    refreshInterval: 3000
  })
 
  if (error) return <p>failed to load</p>
  if (isLoading) return <p>loading...</p>
  return <p>Current status: {data.status}</p>
}

Running the Example Locally

The official example flow starts by downloading only the examples/refetch-interval directory from the repository archive, entering that directory, installing dependencies, and starting the development server. The same local-development expectations are echoed by the E2E site README: run a development command such as npm run dev, yarn dev, or pnpm dev, then open http://localhost:3000 in a browser. In a Next.js example, editing the page updates the browser during development, so it is easy to change the interval duration and watch the resulting network behavior. Sources: e2e/site/README.md

curl https://codeload.github.com/vercel/swr/tar.gz/main | tar -xz --strip=2 swr-main/examples/refetch-interval
cd refetch-interval
yarn
yarn dev
# or
npm install
npm run dev

The E2E site README also explains the API-route convention used by Next.js projects: files under pages/api map to /api/* endpoints instead of React pages. That matters for interval refetching because the clearest demonstration is a local API route whose response changes over time, such as a timestamp, counter, random value, or simulated job state. The React page polls that endpoint through useSWR, while the API route provides fresh server data for each request. Sources: e2e/site/README.md

Implementation Flow

Start with the baseline quick-start shape from the README: import useSWR, call it with a key and fetcher, and branch on error, isLoading, and data. Then add refreshInterval to the options object as the recipe-specific behavior. For demonstration, use a short interval such as three seconds so changes are visible in the browser and network panel. For production, choose a period that reflects user value and backend cost rather than simply polling as fast as possible. Sources: README.md

Next, make the API response visibly change. In a Next.js app this can be done with an API route such as /api/status that returns the current time or a generated status field. Because pages/api files are API routes, the client can use the same URL string as the SWR key and as the fetcher input. This keeps the example close to the README’s description of the key as a unique request identifier, normally the API URL. Sources: README.md, e2e/site/README.md

Finally, verify the behavior by leaving the page open. The first render should show the loading branch until the initial fetch resolves. After that, the page should continue showing the latest successful data while SWR schedules the next request. If the server response changes, the rendered value should update automatically. If the request fails, the component can render its error branch while the rest of the app keeps using SWR’s cache and revalidation machinery. Sources: README.md

System-to-Code Mapping

ConceptWhat the reader seesSource-backed anchor
React Hook entrypointimport useSWR from 'swr' and call it inside a componentREADME.md quick-start hook usage
Cache keyA URL-like string such as /api/status identifies the requestREADME.md describes the key as the unique request identifier
FetcherAn asynchronous function receives the key and returns dataREADME.md explains that the fetcher accepts the key and resolves data
Polling behaviorrefreshInterval causes repeated revalidation on a timerREADME.md lists polling as a built-in SWR capability
Local developmentStart a Next.js dev server and open the app in a browsere2e/site/README.md development-server instructions
API endpointpages/api files are served under /api/*e2e/site/README.md API-route convention

Practical Guidance and Tradeoffs

Use interval refetching when freshness has ongoing value while the user is looking at the page. It is often better than manual refresh buttons for operational screens because the UI updates without extra interaction. It is also simpler than setting up a subscription when the backend only exposes ordinary HTTP endpoints. However, polling still creates repeated requests, so the interval should be long enough to avoid unnecessary backend pressure and short enough to satisfy the product requirement. The example is a teaching tool; real applications should tune the number deliberately.

Prefer polling read endpoints, not mutation endpoints. A fetcher used by useSWR should be safe to call repeatedly, because the interval may run for as long as the component is mounted. If the operation changes server state, use SWR’s mutation APIs instead of putting that operation behind a polling fetcher. Keeping reads and writes separate makes the interval behavior predictable: every tick asks the server for the current representation, and SWR decides when the component should rerender from the resulting data.

When debugging, separate three questions. First, is the component mounted and using the expected key? Second, does the fetcher return a promise that resolves to the data shape the renderer expects? Third, is the endpoint reachable in the local app? The README’s quick-start state branches help isolate the first two issues, while the E2E site README’s Next.js API-route notes help isolate local routing problems. If /api/status does not respond directly in the browser, SWR cannot successfully poll it from the component. Sources: README.md, e2e/site/README.md

Next Steps

After this recipe, read the broader revalidation material to understand how polling combines with focus revalidation, reconnect revalidation, and manual mutation. Then compare this example with prefetch and preload patterns: polling keeps an already-mounted view fresh, while prefetching prepares data before a future view needs it. For API-level details, continue to the useSWR reference and the global configuration page, because interval behavior can be set per hook or coordinated through shared configuration depending on the app structure.

Related pages: quick-start, revalidation-strategies, api-use-swr, api-swr-config, example-prefetch-preload.