This content originally appeared on Bram.us and was authored by Bramus!
From the Next.js folks comes SWR, a React Hooks library for data fetching built on Suspense:
The name “SWR” is derived from
stale-while-revalidate
, a cache invalidation strategy popularized by HTTP RFC 5861. SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
It can avoid scenarios where you need to pass down a fetched user
into several child components
import useSWR from 'swr'
const fetcher = (...args) => fetch(...args).then(res => res.json())
function useUser (id) {
const { data, error } = useSWR(`/api/user/${id}`, fetcher)
return {
user: data,
isLoading: !error && !data,
isError: error
}
}
// page component
function Page () {
return <div>
<Navbar />
<Content />
</div>
}
// child components
function Navbar () {
return <div>
...
<Avatar />
</div>
}
function Content () {
const { user, isLoading } = useUser()
if (isLoading) return <Spinner />
return <h1>Welcome back, {user.name}</h1>
}
function Avatar () {
const { user, isLoading } = useUser()
if (isLoading) return <Spinner />
return <img src={user.avatar} alt={user.name} />
}
With SWR being used, this will result in only 1 request to /api/user/${id}
.
The most beautiful thing is that there will be only 1 request sent to the API, because they use the same SWR key and the request is deduped, cached and shared automatically.
SWR — React Hooks library for data fetching →
This content originally appeared on Bram.us and was authored by Bramus!
Bramus! | Sciencx (2021-03-14T23:17:35+00:00) SWR — React Hooks library for data fetching. Retrieved from https://www.scien.cx/2021/03/14/swr-react-hooks-library-for-data-fetching/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.