useSWR best react hook fetch library!

What is SWR?

useSWR it’s a vercel library “stale-while-revalidate” the official definition:

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
//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>)}
//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>
)}
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 focused
  • revalidateOnReconnect = true: automatically revalidate when the browser regains a network connection (via navigator.onLine)
  • refreshInterval = 0: polling interval (disabled by default)
  • refreshWhenHidden = false: polling when the window is invisible, (if refreshInterval is enabled)
  • refreshWhenOffline = false: polling when the browser is offline, (determined by navigator.onLine)
  • shouldRetryOnError = true: retry when fetcher has an error (details)
  • dedupingInterval = 2000: dedupe requests with the same key in this time span
  • focusThrottleInterval = 5000: only revalidate once during a time span
  • loadingTimeout = 3000: timeout to trigger the onLoadingSlow event
  • errorRetryInterval = 5000: error retry interval (details)
  • errorRetryCount: max error retry count (details)
  • onLoadingSlow(key, config): callback function, when a request takes too long to load (, see loadingTimeout)
  • onSuccess(data, key, config): callback function when a request finishes successfully
  • onError(err, key, config): callback function when a request returns an error
  • onErrorRetry(err, key, config, revalidate, revalidateOps): handler for error retry
  • compare(a, b): comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default, dequal/lite is used.

Software Engineer