Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 23, 2022 06:05 am GMT

How to Use SWR with React


If You are Front End Developer, of Ofcourse you Use the Axios Library at Least Once in Your Projects.
Axios is Nice and One of the Best Libs that Dealing With APIs, But If I told You that There is a Library That is Better than Axios.
So, Let's Get Started...

What is SWR?

SWR is a Shortcut for stale-while-revalidate and Its a React Hooks library for remote data fetching.

SWR Contain Three Main Stages:
1- Steal: Return Data from Cache.
2- Revalidate Send a Fetch Request.
3- Finally comes with the up-to-date data.

Now If You Wonder, Why I should use SWR?
I am still Fine With Axios.

The Thing That You should Know that SWR is not Like Axios, You can Think That It is a Superset of Axios, So You can use Axios as a part of it.
SWR contains a Lot of Features That Axios Did not Have like:

  • Fast, lightweight and reusable data fetching
  • Built-in cache and request deduplication
  • Real-time experience
  • Transport and protocol agnostic
  • SSR / ISR / SSG support-TypeScript ready
  • React Native
  • Fast page navigation
  • Polling on interval
  • Data dependency
  • Revalidation on focus
  • Revalidation on network recovery
  • Local mutation (Optimistic UI)
  • Smart error retry
  • Pagination and scroll position recovery
  • React Suspense
  • ...etc

SWR use React Suspense Technique which prevents React Component from being Rendered Until the Response is Ready and During This Time Give You a Fallback Value.

SWR Installation?

First Create React Project by the Following Command in Your Terminal:

npx create-react-app ./swr-project && cd swr-project

Then install SWR by Following Command:

npm i swr

After Knowing What is React SWR and How to Install it in Your Project, Let's get an example of it.

//* Importsimport axios from "axios";import useSWR from "swr";//* Set Axios Base URLconst apiEndPoint = "";axios.defaults.baseURL = apiEndPoint;//* Fetcher Functionconst fetcher = (url) => axios.get(url).then((res) =>;function Users() {  const { data: users, error } = useSWR("/users", fetcher);  if (error) return <h1>Error!</h1>;  if (!users) return <h1>Loading...</h1>;  return (    <div>      <h1>Users</h1>      { => {        return <h2>{}</h2>;      })}    </div>  );}export default Users;

In The Above Example, We Use useSWR React Hook to fetch users data from a JSON Placeholder Website which gives us fake APIs.
As we see useSWR() Hook takes Two arguments:

  1. URL and its API End Point (in our case Users API)
  2. Fetcher Function this is the function that SWR uses to fetch the data from different APIs.You can use any library as Fetcher Function like fetch() or Axios ..etc

And Give Us two Values:

  1. Data
  2. Error

As I told You before SWR use React Suspense Technique so we can add a fallback value to show it until the data is fetched successfully, in our example we just show Loading... Word but you can replace it with nice loading animations.
So run your project to see the following result.

Users Fetching

Notice that you should handle error and loading values before your react component main content.

Make fetch function Global

One of the SWR features is that you can make the fetch function global in your project.
SWR introduces to us a Context called SWRconfig which gets the fetcher function and shares it between all project components, let's get an example to understand.


//* Importsimport React from "react";import { SWRConfig } from "swr";import axios from "axios";import Users from "./Users";//* Set Axios Base URLaxios.defaults.baseURL = "";function App() {  const fetcher = (url) => axios.get(url).then((res) =>;  return (    <SWRConfig      value={{        fetcher,      }}    >      <Users />    </SWRConfig>  );}export default App;

For in App component, we import SWRconfig Contact from SWR and then we wrapped the App component in it, then we add the fetcher function.

Now we can use SWR in our components without the fetcher function in the Users Component.


//* Importsimport useSWR from "swr";function Users() {  const { data: users, error } = useSWR("/users");  if (error) return <h1>Error!</h1>;  if (!users) return <h1>Loading...</h1>;  return (    <div>      <h1>Users</h1>      { => {        return <h2>{}</h2>;      })}    </div>  );}export default Users;

Make Your Fetcher function by SWR.

Now let's make our Fetcher function to use in future projects.
Our function will get the URL and return three main values:

  1. Data
  2. IsError
  3. isLoading
//* Importsimport useSWR from "swr";import axios from "axios";//* Fetcher Functionconst fetcher = (url) => axios.get(url).then((res) =>;const useFetch = (url) => {  const { data, error } = useSWR(url, fetcher);  return {    data: data,    isLoading: !data && !error,    isError: error,  };};export default useFetch;

Notice That our Fetcher Function uses an useSWR() hook so you should use it only in react components.


Finally, we just know a small introduction about SWR because it has a lot of other features like pagination and Revalidations...etc, that you should try and know it.
See You in the Next Article.

Original Link:

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To