"SWR"이라는 이름은 HTTP RFC 5861에 의해 알려진 HTTP 캐시 무효 전략인 stale-while-revalidate에서 유래되었습니다. SWR은 먼저 캐시(스태일)로부터 데이터를 반환한 후, fetch 요청(재검증)을 하고, 최종적으로 최신화된 데이터를 가져오는 전략입니다.
단 한 줄의 코드로 프로젝트 내의 데이터 가져오기 로직을 단순화할 수 있으며, 다음과 같은 모든 놀라운 기능들을 바로 사용할 수도 있습니다.
npm install swr
or
yarn add swr
// _app.tsx
import { fetcher } from "~/your_repo/fetcher";
import { SWRConfig, type SWRConfiguration } from "swr";
const MyApp({ Component, pageProps }: AppProps) {
const { fallback } = pageProps;
const option: SWRConfiguration = {
fetcher,
fallback: fallback || {},
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
// 404에서 재시도 안함
if (error.status === 404) return
// 특정 키에 대해 재시도 안함
if (key === '/api/user') return
// 10번까지만 재시도함
if (retryCount >= 10) return
// 5초 후에 재시도
setTimeout(() => revalidate({ retryCount }), 5000)
}
};
return (
<SWRConfig value={{ fallback }}>
<Components {...pageProps} />
</SWRConfig>
)
}
// your_repo/fetcher.ts
import axios from "axios";
export const fetcher = (url, token = "", params = {}) => {
return axios.get(url, { params, headers: token ? { authorization: `Bearer ${token}` } : {} })
.then((res) => res.data);
};
fetcher 와 fallback 은 다음 포스팅에서 좀 더 자세히 다루어 보겠습니다.