nextjs

nextjs useSWR 사용법

직장인코딩 2022. 10. 12. 23:17
반응형

 

SWR은 react-query 처럼 api를 fetch 하는 일종의 라이브러리라고 볼 수 있습니다.

그런데 SWR의 장점이 참 많습니다.

SWR은 한번 fetch해온 data는 메모리에 담아두고 담아둔 data를 그냥 그 페이지에 갔을 때 보여주기 때문에 페이지를 이동할때마다 fetch를 하는 것 보다 훨씬 빠르게 페이지를 render를 할 수 있게 됩니다.

 

사용방법은 일단 아래 코드와 같습니다.

 

const {data} = useSWR("API URL", fetcher함수)
 

data를 비구조화 할당으로 받아주고 useSWR에 1번째 인자로

API의 URL을 넣어주고 2번쨰 arg로 fetcher 함수를 만들어 넣어줍니다.

 

fetcher함수는 arg로 무조건 저기 “API URL”이 들어가게 실행이 되는데요 예를 들자면

 

const {data} = useSWR("/api/items", fetcher)

이렇게 있다면

fetcher 안에 arg로 "/api/items"가 들어간 상태로 실행된다는 것입니다.

fetcher을 만들어 본다면

const fetcher= (url:string) => {
	return fetch(url).then((res) => res.json())
}

이런식으로 저기 url에 "/api/items"가 들어가서 실행이 된다는

것입니다.
 

그러면 data에 api로 받아온 data가 저장되게 됩니다.

근데 사실 이렇게 fetcher함수를 일일이 정의를 하고 이럴 필요가 없습니다.

본인이 만든 페이지에 최상위에서 render시켜주는 tsx로 가서

나머지 page들을 감싸주면되는데요

 

nextjs에서 최상의 상단 page는 _app.tsx 라고 할 수 있는데 보통

내용이

 

import "../styles/globals.css";
import type { AppProps } from "next/app";


function MyApp({ Component, pageProps }: AppProps) {
  return (
        <Component {...pageProps} />
  );
}

export default MyApp;
 

이렇게 되있습니다.

여기에 저기 component를 감싸주면 되겠지요

그떄 사용하는 것이 SWRconfig 인데요 일단 import를 해준뒤

component를 감싸줍니다.

 

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { SWRConfig } from "swr";



function MyApp({ Component, pageProps }: AppProps) {
  return (
		<SWRConfig>
        <Component {...pageProps} />
		</SWRConfig>
  );
}

export default MyApp;
 

근데 SWRConfig에 value값이 꼭 필요한데 이 value값에 fetcher함수를 넣어주면 되는 것입니다.

아까 만든 그거요!

 

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { SWRConfig } from "swr";
const fetcher = (url: string) => {
  return fetch(url).then((res) => res.json());
};
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <SWRConfig
      value={{
        fetcher,
      }}
    >
      <div className="w-full max-w-xl mx-auto">
        <Component {...pageProps} />
      </div>
    </SWRConfig>
  );
}

export default MyApp;
 

이렇게 하면 저희가 처음에 정의했던 code

 

const {data} = useSWR("/api/items", fetcher)
 

이 코드에 fetcher을 빼도 됩니다.

 

const {data} = useSWR("/api/items")
 

이런 식으로요!

감사합니다~!

 

반응형