9월 22일 수요일

< yujin />·2021년 9월 22일
0

일일회고

목록 보기
8/10
post-thumbnail

😎 알게된것

Next.js의 Page 렌더링 방식

1. Pre-Rendering

  • 더 나은 성능, SEO를 위해 넥스트는 page를 위한 HTML을 사전에 만드는 것을 원칙으로 한다.
  • 언제 HTML를 만드느냐에 따라 다음 두가지로 나뉜다.
    • Static Generation : build 할 때 생성 (product ver 에서는 next build 하면 생성됨) 해서 request 때마다 재사용
    • Server Side Rendering : request 할 때마다 각각 생성
  • next는 Static Generation을 권장하고있다. 유저의 요청에 앞서서 페이지가 렌더링 되어야 하는가? 라고 자문했을때 yes 라면 Static Generation을 권장!

2. Static Generation

2-1. Without Data

2-2. With Data

  • getStaticProps : page content가 외부 data에 의존할 때 사용
    • build 때 호출됨
    • 이런식으로 return 해주며, props.posts로 컴포넌트에서 props로 받을 수 있음
function Blog({ posts }) {
  // Render posts...
}

// This function gets called at build time
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
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

export default Blog
  • getStaticPaths : page 경로가 외부 data에 의존할 때 사용 (dynamic routing)
    • pages/posts/[id] 이런 경우에 사용
  // 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()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}

3. SSR

  • getServerSideProps 사용
    • 위 두 함수와 유사하지만, 차이점은 얘는 build 때 호출 되는게 아니라, 유저의 request 때마다 매번 호출된다.
function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

Reference

profile
잘하진 않지만 포기하진 않을거햐

0개의 댓글