Sean's Blog

An image showing avatar

Hi, I'm Sean

這裡記錄我學習網站開發的筆記
歡迎交流 (ゝ∀・)b

LinkedInGitHub

一起來試試看 NextJS 的 "useSWR" Hook 吧!

最近看 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:

1import useSWR from 'swr'
2
3useSWR(<request-url>, (url) => fetch(url).then(res => res.json()))
4

範例一:

1const fetcher = (url) => fetch(url).then((r) => r.json());
2
3function App() {
4  const { data, error } = useSWR('/api/data', fetcher);
5  // ...
6}
7

範例二:

1const { data, error } = useSWR(
2  'https://nextjs-course-c81cc-default-rtdb.firebaseio.com/sales.json',
3  (url) => fetch(url).then((res) => res.json()),
4);
5

亦或是使用全局配置,就能在使用時省略不寫第二個參數 fetcher

Global Configuration – SWR

👉 使用 SWR 相較於使用 fetch 或 Axios 的好處是,它內建提供了的緩存和重新整理等機制,使得資料的獲取和更新變得更加簡單且有效率。此外,它還具有自動並行請求、錯誤重試和狀態管理等功能,使得資料管理更加方便。