Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
The swr npm package is a React Hooks library for remote 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.
Data Fetching
SWR provides a hook called useSWR for data fetching. You can pass a key and a fetcher function, and it will return the data, error, and other useful values for handling the UI state.
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return <div>Hello, {data.name}!</div>
}
Automatic Revalidation
SWR automatically revalidates data when a user focuses on the window or when the network is reconnected. It can also be configured to revalidate data at a fixed interval.
import useSWR from 'swr'
function Profile() {
const { data } = useSWR('/api/user', fetcher, {
refreshInterval: 3000
})
// data will be revalidated every 3 seconds
return <div>{data.name}</div>
}
Local Mutation
SWR allows you to mutate the local data immediately and revalidate it in the background. This provides an optimistic UI update experience.
import useSWR, { mutate } from 'swr'
function updateUsername(name) {
mutate('/api/user', { ...data, name }, false)
fetch('/api/user', {
method: 'POST',
body: JSON.stringify({ name })
}).then(() => {
mutate('/api/user')
})
}
React Query is another library for fetching, caching, and updating data in React applications. It provides more advanced features like query cancellation, background fetching, and even pagination helpers. React Query is often compared to SWR for its similar use cases but offers a different API and additional features.
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It is more complex and powerful than SWR, designed specifically for GraphQL, and provides features like caching, optimistic UI, and subscription support.
Axios is a promise-based HTTP client for the browser and Node.js. While it is not a hook-based data fetching library like SWR, it is often used for making HTTP requests in React applications. Developers would use Axios for fetching data and then manage the caching and state themselves or with additional libraries.
SWR is a React Hooks library for remote data fetching.
The name “SWR” is derived from stale-while-revalidate
, a HTTP cache invalidation strategy popularized by 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 features:
With SWR, components will get a stream of data updates constantly and automatically, Thus, the UI will be always fast and reactive.
import useSWR from 'swr'
function Profile () {
const { data, error } = useSWR('/api/user', fetch)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
In this example, the React Hook useSWR
accepts a key
and a fetch
function.
key
is a unique identifier of the data, normally a URL of the API. And the fetch
accepts
key
as its parameter and returns the data asynchronously.
useSWR
also returns 2 values: data
and error
. When the request (fetch) is not yet finished,
data
will be undefined
. And when we get a response, it sets data
and error
based on the result
of fetch
and rerenders the component.
Note that fetch
can be any asynchronous function, so you can use your favourite data-fetching
library to handle that part.
useSWR
const {
data, // data for the given key (or undefined)
error, // error (or undefined)
isValidating, // if the request is loading
revalidate // function to trigger a validate manually
} = useSWR(
key, // a unique key for the data
fn, // Promise returning function to fetch your data
swrOptions? = {
suspense: false, // enabled React Suspense mode
revalidateOnFocus: true, // auto revalidate when window gets focused
refreshWhenHidden: false, // refresh while the window is invisible
shouldRetryOnError: true, // retry when fetch has an error
refreshInterval: 0, // polling interval (disabled by default)
errorRetryInterval: 5000, // error retry interval (10s on slow network)
focusThrottleInterval: 5000, // keep focus revalidate requests in a time window
dedupingInterval: 2000, // deduping requests
loadingTimeout: 3000, // timeout for triggering the onLoadingSlow event
onLoadingSlow, // event handlers
onSuccess,
onError,
onErrorRetry,
fetcher // default fetcher function (same as `fn`)
}
)
SWRConfig
A context to provide global configurations (swrOptions
) for SWR.
import useSWR, { SWRConfig } from 'swr'
function App () {
// all the SWRs inside will use `refreshInterval: 1000`
return <SWRConfig value={{ refreshInterval: 1000 }}>
<Profile/>
</SWRConfig>
}
function Profile () {
const { data, error } = useSWR('/api/user', fetch)
// ...
}
mutate
With mutate
, you can update your local data programmatically, while
revalidating and finally replace it.
import useSWR, { mutate } from 'swr'
function Profile () {
const { data } = useSWR('/api/user', fetch)
return <div>
<h1>My name is {data.name}.</h1>
<button onClick={async () => {
const newName = data.name.toUpperCase()
// send a request to the API to update the data
await requestUpdateUsername(newName)
// update the local data immediately and revalidate (refetch)
mutate('/api/user', { ...data, name: newName })
}}>Uppercase my name!</button>
</div>
}
trigger
You can broadcast a revalidation message to all SWR data inside any component by calling
trigger(key)
.
import useSWR, { trigger } from 'swr'
function App () {
return <div>
<Profile />
<button onClick={() => {
// set the cookie as expired
document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
// tell all SWRs with this key to revalidate
trigger('/api/user')
}}>
Logout
</button>
</div>
}
You can enable the suspense
option to use useSWR
with React Suspense.
import { Suspense } from 'react'
import useSWR from 'swr'
function Profile () {
const { data } = useSWR('/api/user', fetch, { suspense: true })
return <div>hello, {data.name}</div>
}
function App () {
return <Suspense fallback={<div>loading...</div>}>
<Profile/>
</Suspense>
}
Thanks to Ryan Chen for providing the awesome swr
npm package name!
The MIT License.
FAQs
React Hooks library for remote data fetching
The npm package swr receives a total of 1,842,139 weekly downloads. As such, swr popularity was classified as popular.
We found that swr demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 8 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.