[React] SWR for data fetching
The name “SWR” is derived from stale-while-revalidate
, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
Example
import React from "react";
import useSWR from "swr";
import { LoadingListings, Listing, ListingsGrid } from "../components";
function Listings(props) {
const {
data: listings,
loading,
error,
} = useSWR("https://my.cms.com/listings", (url) =>
fetch(url).then((r) => r.json())
);
if (loading) {
return <LoadingListings />;
}
return (
<ListingsGrid>
{listings.map((listing) => (
<Listing listing={listing} />
))}
</ListingsGrid>
);
}