SWR is a popular library which provides React Hooks for Data Fetching.
Installation
Inside your React project directory, run the following:
1 | npm i swr |
If you’re using yarn:
1 | yarn add swr |
Quick Start
For normal RESTful APIs with JSON data, first you need to create a fetcher function, which is just a wrapper of the native fetch:
1 | const fetcher = (...args) => fetch(...args).then((res) => res.json()); |
If you’re using Axios:
1 | import axios from "axios"; |
Normally, there’re 3 possible states of a request: “loading”, “ready”, or “error”. You can use the value of data
, error
and isLoading
to determine the current state of the request, and return the corresponding UI.
Make It Reusable
When building a web app, you might need to reuse the data in many places of the UI. It is incredibly easy to create reusable data hooks on top of SWR:
1 | function useUser(id) { |
And use it in your components:
1 | function Avatar({ id }) { |
By adopting this pattern, you can forget about fetching data in the imperative way: start the request, update the loading state, and return the final result. Instead, your code is more declarative: you just need to specify what data is used by the component.
API
1 | const { data, error, isLoading, isValidating, mutate } = useSWR( |
The key
is required, it’s a unique key string for the request (or a function / array / null). The rest arguments are optional.
You can set initial data to be returned when the request is loading with the fallbackData
attribute in the options.
1 | import useSWR from "swr"; |
Demo: