본문 바로가기

Front-end/React

Next.js

Pages


Pre-rendering

  • default 가 모든 페이지를 pre-render(각각의 페이지들을 HTML로 생성)함
  • 아래 두가지 형태가 있고 HTML 생성 시점에 따라 다름
  • 각 페이지 마다 다른 pre-render 방식을 절정하여 hybrid 한 app 을 만들 수 있음

Static Generation

  • build 시점에 HTML을 생성하고 각 request마다 재사용됨
  • “next build”시 생성

static generation with data

  1. 해당 페이지에 외부에서 받는 데이터가 있는경우
    1. 같은 파일 내에 async 함수인 ‘getStaticProps’ 를 같은 파일 내에서 export 시킴
export default function Blog({ posts }) {
  // Render posts...
}

// 빌드 시점에 호출
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // api 통신 결과인 'posts'를 빌드 시점에 받아서 Blog component 에 전달
  return {
    props: {
      posts,
    },
  }
}

2. 해당 페이지의 path가 외부 데이터에 의존적인 경우

  • dynamic routes의 경우 path에 따라 결과 HTML 이 달라짐
  • 같은 파일 내에 async 함수인 ‘getStaticPaths’ 를 같은 파일 내에서 export 시킴
// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // pre-render 할 path들을 통신해온 posts에 대해 생성
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))

  // 빌드시점에는 이 path들만 pre-render함
  // { fallback: false } 은 다른 routes들은 404로 응답할것을 뜻함
  return { paths, fallback: false }
}

Server-side Rendering

  • 각 request 마다 HTML을 생성
  • data의 update 가 자주 일어나는 페이지
  • page의 content가 매 request마다 달라지는 경우 사용
  • 같은 파일 내에 async 함수인 ‘getServerSideProps’ 를 같은 파일 내에서 export 시킴
export default function Page({ data }) {
  // Render data...
}

// 매 request 마다 호출됨
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // page에 props로 전달
  return { props: { data } }
}

 

참고자료

https://nextjs.org/docs/getting-started

'Front-end > React' 카테고리의 다른 글

Styled-component  (0) 2022.12.05
React Query  (0) 2022.11.28
Redux  (0) 2022.11.23
Hook  (0) 2022.11.23
React core  (0) 2022.11.23