Data fetching with SWR
- React course
- Advanced
- Lesson 17/56
- 4 min
Learn to fetch cached data with SWR.
What is SWR?
SWR (stale-while-revalidate) is Vercel's cached data-fetching library. A useSWR call fetches the data, caches it and revalidates in the background.
SWR shares the data across every component that uses the same key; one request updates many components. This makes server state management easy.
SWR offers auto retry, refetch on focus and pessimistic updates out of the box.
The useSWR call
useSWR takes two parameters: a key (usually a URL) and an optional fetcher function. The return value is the { data, error, isLoading } object.
On first render isLoading is true; when data arrives data fills and isLoading turns false. On error error is set.
As long as the key matches, SWR uses the cache; this makes data appear instantly across page navigations.
Practice ProductList with useSWR
Complete the skeleton. Write a ProductList component. Use useSWR to fetch '/api/products' (use (url) => fetch(url).then(r => r.json()) as fetcher). If isLoading render <p>Loading</p>, if error render <p>Error</p>, otherwise render <ul> with products.map(p => <li key={p.id}>{p.name}</li>). Add export default.
Starter code
import useSWR from 'swr';
// Write ProductList hereSample solution
import useSWR from 'swr';
function ProductList() {
const { data: products, error, isLoading } = useSWR(
'/api/products',
(url) => fetch(url).then((r) => r.json())
);
if (isLoading) return <p>Loading</p>;
if (error) return <p>Error</p>;
return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
export default ProductList;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does SWR stand for?
It shows stale cached data while revalidating in the background.- stale-while-revalidate Correct answer
- state-with-reducer
- sync-web-request
- server-worker-render
Explanation: SWR stands for stale-while-revalidate.
2 useSWR return value
const { data, error, ____ } = useSWR('/api/products', fetcher);
const { data, error, isLoading } = useSWR('/api/products', fetcher);
Explanation: isLoading is one of useSWR's three states.
3 Data fetching with SWR: match the terms
| Term | Meaning |
|---|---|
useSWR |
Fetches data |
data |
Returned data |
error |
Error object |
isLoading |
Is loading |