SSR + SWR

훈나무·2022년 12월 4일
0

nextjs

목록 보기
6/9
post-thumbnail

SSR + SWR

getServerSideProps 을 사용해서 ssr을 사용할 수 는 있지만, 클라이언트의 PC에 저장되는 SWR을 사용할 수 없었습니다.

페이지를 미리 렌더링해야 하는 경우 Next.js는 2가지 형태의 사전 렌더링을 지원합니다.
Static Generation (SSG), Server-side Rendering (SSR).

SWR를 사용하면서, SEO를 위해 페이지를 미리 렌더링할 수 있으며 클라이언트 측에서 caching, revalidation, focus tracking, refetching와 같은 기능도 사용할 수 있습니다.

import Head from "next/head";
import useSWR, { SWRConfig } from "swr";


const Home: NextPage = () => {
  const { user, isLoading } = useUser();
  const { data } = useSWR<ProductsResponse>("/api/products");
  return (
    <Layout title="홈" hasTabBar>
      <div className="flex flex-col space-y-5 divide-y">
        {data
          ? data?.products?.map((product) => (
              <Item
                id={product.id}
                key={product.id}
                title={product.name}
                price={product.price}
                hearts={product._count?.favs || 0}
                image={product.image}
              />
            ))
          : "Loading..."}
      </div>
    </Layout>
  );
};

const Page = ({ products }) => {
  return (
    <SWRConfig
      value={
        fallback: {
          "/api/products": {
            ok: true,
            products,
          },
        },
      }}
    >
      <Home />
    </SWRConfig>
  );
};

export async function getServerSideProps() {
  const products = await client.product.findMany({});
  return {
    props: {
      products: JSON.parse(JSON.stringify(products)),
    },
  };
}

export default Page;

설명

SWRConfig 에 value 값으로 초기값을 설정해 줍니다.
기존의 SWR은 클라이언트에서 값을 호출하지만, SSR로 변경해보겠습니다.
getServerSideProps 을 통해서, 페이지가 로드되기 전에 products 데이터를 받아오고 있습니다. 그 데이터를 SWRConfig 에서 초기값으로 설정해줍니다.
이렇게 하면, 페이지가 로드 되기 전에 이미 캐시값을 가지고 있게 됩니다.

profile
프론트엔드 개발자 입니다

0개의 댓글