最近看 React Developer Roadmap 發現 API Calls 人家推薦 SWR 這套工具,好奇到底是什麼功能居然能撼動 Axios 的地位?試用了一下發現還真有點意思!
什麼是 SWR
SWR is a React Hooks library for data fetching.
The name “SWR” is derived from stale-while-revalidate
, a cache invalidation strategy popularized by HTTP RFC 5861. SWR first returns the data from cache (stale), then sends the request (revalidate), and finally comes with the up-to-date data again.
With just one hook, you can significantly simplify the data fetching logic in your project.
使用 SWR
You must now add a default “fetcher” when working with useSWR:
import useSWR from 'swr'
useSWR(<request-url>, (url) => fetch(url).then(res => res.json()))
範例一:
const fetcher = (url) => fetch(url).then((r) => r.json());
function App() {
const { data, error } = useSWR("/api/data", fetcher);
// ...
}
範例二:
const { data, error } = useSWR(
"https://nextjs-course-c81cc-default-rtdb.firebaseio.com/sales.json",
(url) => fetch(url).then((res) => res.json()),
);
亦或是使用全局配置,就能在使用時省略不寫第二個參數 fetcher
:
👉 使用 SWR 相較於使用 fetch 或 Axios 的好處是,它內建提供了的緩存和重新整理等機制,使得資料的獲取和更新變得更加簡單且有效率。此外,它還具有自動並行請求、錯誤重試和狀態管理等功能,使得資料管理更加方便。