Next.js에서 SWR 사용하기

지혜·2023년 8월 17일
1

1. SWR 시작하기

공식문서 : https://swr.vercel.app/ko

SWR을 설치합니다.

npm install swr
또는
yarn add swr

그 다음, useSWR을 import하고 아래 코드와 같이 사용할 수 있습니다.
fetcher는 fetch할 때 어떤 방식(fetch, axios 등)으로 사용할지 설정할 수 있습니다.

const fetcher = (...args) => fetch(...args).then(res => res.json())

const { data, error, isLoading } = useSWR('/api/user/123', fetcher)

2. SWR Context 만들기

하지만 모든 곳에서 fetcher를 설정해주는 것은 번거롭기 때문에 Context를 사용하여 fetcher를 전역으로 설정할 수 있습니다.

SWR은 CSR 환경에서 동작하기 때문에 별도의 Context 파일을 생성해준 뒤 layout.tsx 파일에서 호출해주도록 합니다.

// src/context/SWRConfigContext.tsx

'use client';

import { SWRConfig } from 'swr';

type Props = {
  children: React.ReactNode;
}

export default function SWRConfigContext({ children }: Props) {
  return <SWRConfig 
  value={{
    fetcher: (url: string) => fetch(url).then((res) => res.json),
  }}>{children}</SWRConfig>
}

생성한 SWRConfigContext로 children을 감싸줍니다.

// src/app/layout.js

...
import SWRConfigContext from '@/context/SWRConfigContext'

...

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    ...
    <SWRConfigContext>{children}</SWRConfigContext>
    ...
  )
}

3. SWR 사용하기

fetcher를 생략하고 아래와 같이 사용할 수 있습니다.

const { data, error, isLoading } = useSWR('/api/user/123')

0개의 댓글