Next.js

[Next.js] 13버전 Data Fetching

킹우현 2023. 8. 21. 00:59

사전 렌더링(Pre-rendering) 복습

미리 각 페이지의 html을 생성하여 SEO 적용할 수 있게 하는 것으로, Next.js 에서는 페이지마다 2가지 렌더링 방법을 선택적으로 사용할 수 있다.

  • 정적 사이트 생성(SSG) : 빌드 시 html 생성해두고 요청이 오면 생성해둔 html 재사용, 빈번한 업데이트 필요 없는 정적 페이지 만들 때 사용 ex) 마케팅, 블로그 게시글, 설명서, 제품 목록 페이지
  • 서버 사이드 렌더링(SSR) : 사용자 각 요청마다 새 html 생성, 요청마다 데이터를 최신상태로 업데이트해야 될 경우 사용

Next.js 13 버전 Data Fetching

fetch() 사용

export default funciton Home(){
  const a = use(fetchData())
  return <>{/* ... */} </>
}
export async function fetchData() {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
  return data
}

async/await을 사용한 fetch() API 사용으로 변경, app 폴더 사용 시 getStaticPropsgetInitialPropsgetServerSideProps 등 이전방법은 해당 폴더에선 지원안됨

👉🏻 fetch 옵션을 통해 getServerSideProps, getStaticProps 처럼 사용 가능 !

fetch() 옵션

fetch('https://url', option)
export default async function Page() {
  // This request should be cached until manually invalidated.
  // Similar to `getStaticProps`.
  // `force-cache` is the default and can be omitted.
  const staticData = await fetch(`https://...`, { cache: 'force-cache' });

  // This request should be refetched on every request.
  // Similar to `getServerSideProps`.
  const dynamicData = await fetch(`https://...`, { cache: 'no-store' });

  // This request should be cached with a lifetime of 10 seconds.
  // Similar to `getStaticProps` with the `revalidate` option.
  const revalidatedData = await fetch(`https://...`, {
    next: { revalidate: 10 },
  });

  return <div>...</div>;
}
  • { cache: 'force-cache' } - 기본값으로 생략가능(getStaticProps와 유사)
  • { cache: 'no-store' } - 모든 요청에서 최신 데이터 받아오기 (getServerSideProps와 유사)
  • { next: { revalidate: 10 } } - 10초 후 새 요청오면 페이지 새로 생성 (revalidate옵션이 있는 getStaticProps와 유사)