There are many ways to fetch remote data in React such as fetch or Axios. SWR is not only fetch data from APIs like others but also possible to do things like caching and refetching in realtime using React Hooks
What is SWR ?
SWR stands for stale-while-revalidate. It’s a library for data fetching in React that works with three main steps: return the cached data ( stale ), then sends the fetch request ( revalidate ), and finally re-update the data. The useSWR hook with reasonable parameters will handle all three steps for us.
Quick Start
We need to install the library first with the following command:
npm install swr
or
yarn add swr
useSWR hook example:
import useSWR from 'swr'const url= “https://quote-garden.herokuapp.com/api/v3/quotes/random"const fetcher = async (url) => await fetch(url).then((res) => res.json())const { data, error } = useSWR(url, fetcher)
Firstly, we start by import useSWR from the library. Secondly I declared the URL of the API that I want to fetch, and a function to fetch the data. Finally I passed the URL and the fetcher function as parameters to the useSWR hook. Now the request will be made and it return two states: the data fetched and the error state.
Other Features of SWR
I just demonstrate how to make a simple request using fetch and SWR. Now we can enhance the data fetching using other features of SWR
Refetch on Interval
This feature allow us to refetch data overtime which would be useful if the data changes regularly. You can enable it with:
useSWR(url, fetcher, { refreshInterval: x }) //x is the time in ms
Revalidate on Reconnect
Imagine you are using the internet and somehow you disconnected. This feature will help you to refetch the data immediately when you connect to the internet successfully. The feature is always enabled on default, but you can turn it off with revalidateOnReconnect parameter
Dedupe Requests
For instance, you have multiple buttons to refetch the data and you want to limit the amount of time for the request to be refetched when users click the buttons. SWR provide you with one option called dedupingInterval to do that
useSWR(url, fetcher, {dedupingInterval: 5000})//you can only refetched after 5s
And many more !
SWR has many more features that I can’t demonstrate them all in this article such as:
- Revalidation on focus
- Fast page navigation
- Pagination
- Suspense mode
- Local mutation
Conclusion
Throughout this article, I just showed why SWR is an awesome library. It allows remote data fetching with simplify advanced features and increases user experience
Thanks for reading
Last Words
Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here