useSWR best react hook fetch library!
What is SWR?
useSWR it’s a vercel library “stale-while-revalidate” the official definition:
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.
useSWR is a React Hook library made by vercel, it’s like axios.js or any other fetch function the principal mission is to manage HTTP request but the have a lot of new features we will see most important one.
Features
- Manage cache ;
- Handle errors ;
- Real-time ;
- Data refresh interval ;
- Page focus & data refreshing.
- …
how to use?
First, we need to install it!
npm install swr //with npm yarn add swr // or with yarn
And now let’s take an example.
//Example 1import React from 'react'
import useSWR, { mutate } from "swr";const fetcher = (...args) => fetch(...args).then((res) => res.json());export default function Component1() {const { data, error } = useSWR("http://localhost:8000/server/get", fetcher, {});
if (!data) return "I am loading..."; if (error) return "there is an error"; const users = data.map(user => { return <li>{user}</li>;});return (<ol>{users}</ol>)}
In this example we import swr and we use a function “fetcher” this function is a simple fetch data function with args. the useSWR returns an object containing data, error, and mutate.
A third argument is an object that we can pass to it some options, we will see it in the second example.
If data is loading the useSwr returns nothing in other hands (!data), if data is coming we’ll treat it like a useState, the component renders again and it will jump to the map function normally, but if the fetcher function has an error like (404 or 500 …) we can handle this exception with error variable.
//Example 2import React from 'react'
import useSWR, {mutate} from "swr";const fetcher = (...args) => fetch(...args).then((res) => res.json());export default function Component1() {const { data, error } = useSWR("http://localhost:8000/server/get", fetcher, { revalidateOnFocus: false, refreshInterval : 2000});if (!data) return "I am loading...";if (error) return "there is an error";const users = data.map(user => {
return <li>{user}</li>;
});return (
<ol>{users}
<button onClick={
async () => {
await fetcher("http://localhost:8000/server/post", {
headers: {'Content-Type': 'application/json'},
method: "POST", body: JSON.stringify({ name:"karimp" }),});
mutate("http://localhost:8000/server/get");
}}
> Click</button>
</ol>
)}
In this example, we are using the mutate function and the third arg, for the revalidateOnFocus we are disabled in this setting.
revalidateOnFocus: revalidateOnFocus = true
auto revalidate when the window gets focused. by default revalidateOnFocus is true.
refreshInterval : polling interval disabled by default. is the time between next auto-refreshing.
mutate function: is for refresh local state data so for example 2 we are sending data to server but the local state data not updated. the mutate function refresh local state data based in the initial endpoint :
useSWR("http://localhost:8000/server/get" .....
More option ( from the official Github repo ):
initialData
: initial data to be returned (note: This is per-hook)revalidateOnMount
: enable or disable automatic revalidation when the component is mounted (by default revalidation occurs on mount when initialData is not set, use this flag to force behavior)revalidateOnFocus = true
: auto revalidate when window gets focusedrevalidateOnReconnect = true
: automatically revalidate when the browser regains a network connection (vianavigator.onLine
)refreshInterval = 0
: polling interval (disabled by default)refreshWhenHidden = false
: polling when the window is invisible, (ifrefreshInterval
is enabled)refreshWhenOffline = false
: polling when the browser is offline, (determined bynavigator.onLine
)shouldRetryOnError = true
: retry when fetcher has an error (details)dedupingInterval = 2000
: dedupe requests with the same key in this time spanfocusThrottleInterval = 5000
: only revalidate once during a time spanloadingTimeout = 3000
: timeout to trigger the onLoadingSlow eventerrorRetryInterval = 5000
: error retry interval (details)errorRetryCount
: max error retry count (details)onLoadingSlow(key, config)
: callback function, when a request takes too long to load (, seeloadingTimeout
)onSuccess(data, key, config)
: callback function when a request finishes successfullyonError(err, key, config)
: callback function when a request returns an erroronErrorRetry(err, key, config, revalidate, revalidateOps)
: handler for error retrycompare(a, b)
: comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default,dequal/lite
is used.
You can see more in documentation in Github.