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 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.

You can see more in documentation in Github.

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to create a blog using Hexo static site generator and free web hosting on GitLab Pages

React Basics — Functional vs Class Components — Part 1 in a 4 Part Series

Create a Click To Tweet Widget With JavaScript.

HangFire - Delayed / Recurring Jobs

Using the integrative genomics viewer (IGV) in Angular

Forget about getElementById() and use meaningful ids

What is Memoization?

Check a user’s network connectivity using JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aboujaafar Othmane

Aboujaafar Othmane

Software Engineer

More from Medium

Create Google map with a marker using react

React JS and Next JS are popular JavaScript tools among front-end developers.

React JS: Overview

Using Emotion in React App