SWR Cache Strategy
Use SWR to cache, revalidate, and dedupe fetches in React, with a focus on key design and the revalidate-on-focus policy for fresh data.
On this page
Introduction
This guide covers SWR cache strategy in React, a recurring concern in the data-fetching scenario. Refetching the same data on every render wastes bandwidth and flickers the UI. SWR caches by key, dedupes in-flight requests, and revalidates on focus or interval, so the UI shows stale data instantly and fresh data a moment later, which is the stale-while-revalidate pattern made into a hook.
Design the key
Make the key include every input the fetch depends on, so a different page or filter is a different cache entry and you never serve stale data for a new input.
The trade-off worth naming is that make the key include every input the fetch depends on, so a different page or filter is a different cache entry and you never serve stale data for a new input adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
import useSWR from 'swr';
const { data } = useSWR(['/api/orders', page, filter], ([url, p, f]) => fetch(url + '?p=' + p + '&f=' + f).then(r => r.json()));
Set revalidate policy
Pick revalidateOnFocus for a tab the user returns to, and dedupingInterval to avoid hammering, so freshness and load are balanced for your data.
The trade-off worth naming is that pick revalidateonfocus for a tab the user returns to, and dedupinginterval to avoid hammering, so freshness and load are balanced for your data adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Optimistic mutate
After a write, call mutate with the expected new data so the UI updates before the refetch, and roll back on error, which is the optimistic pattern.
The trade-off worth naming is that after a write, call mutate with the expected new data so the ui updates before the refetch, and roll back on error, which is the optimistic pattern adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
mutate('/api/orders', [...orders, newOrder], false);
try { await post(newOrder); } catch { mutate('/api/orders'); }
Error retry
SWR retries on error by default; cap the count so a down endpoint does not retry forever, and show an error state after the budget is spent.
The trade-off worth naming is that swr retries on error by default; cap the count so a down endpoint does not retry forever, and show an error state after the budget is spent adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Prefetch
Warm the cache for a route the user is likely to navigate to with a prefetch fetch, so the next page renders instantly from cache.
The trade-off worth naming is that warm the cache for a route the user is likely to navigate to with a prefetch fetch, so the next page renders instantly from cache adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Test revalidation
Render, refocus the window, and assert a refetch fires, then change the key and assert a new fetch, so the cache policy is exercised.
The trade-off worth naming is that render, refocus the window, and assert a refetch fires, then change the key and assert a new fetch, so the cache policy is exercised adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.
Sources
Sources: SWR docs, stale-while-revalidate.
FAQ
- What should the SWR key be?
- A string or array that uniquely identifies the data and includes every variable the fetch depends on, so a different variable is a different cache entry rather than a stale one.
- When does revalidateOnFocus help?
- When the user returns to the tab and you want fresh data without a manual refresh; turn it off for high-traffic or write-heavy data where it would revalidate too often.
Report a problem with this articleOpens a pre-filled issue on GitHub.