개발story

TIL # 64 < Next.js 기초 (2) > 본문

Learn/Today I Learn

TIL # 64 < Next.js 기초 (2) >

미래개발자 2023. 1. 31. 17:59
728x90
  • SSG(Static-Site Generation) 실습 - getStaticProps, getStaticPaths)</aside>
    • getStaticProps
      export async function getStaticProps(context) {
        return {
          props: {}, // will be passed to the page component as props
        }
      } 
      
      • getStaticProps 함수는 Server에서만 실행됩니다. Browser에서는 실행되지 않습니다.
      • getStaticProps 함수는 build 하는 그 순간만 실행됩니다.
      • getStaticProps에서는 getServerSideProps에서 context를 통해 쉽게 query에 접근한 것과는 다르게 dynamic routing을 지원하려면 특별한 방법이 필요합니다.
      • getStaticProps의 return 값은 Post page의 props로 전달됩니다.
    • SSG를 원하는 페이지에 getStaticProps를 추가하면, 해당 페이지는 빌드할 때 렌더링 됩니다.
    • getStaticPaths
      // pages/posts/[id].js
      
      // Generates `/posts/1` and `/posts/2`
      export async function getStaticPaths() {
        return {
          paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
          fallback: false, // can also be true or 'blocking'
        }
      }
      
      // `getStaticPaths` requires using `getStaticProps`
      export async function getStaticProps(context) {
        return {
          // Passed to the page component as props
          props: { post: {} },
        }
      }
      
      export default function Post({ post }) {
        // Render post...
      }
      
      • getStaticPaths에서는 getStaticProps 가 있어야 실행되고, getStaticPaths의 return 값은 getStaticProps의 props로 전달됩니다.
    • getStaticProps을 이용하는 페이지에서 dynamic routes를 제공하기 위해서 사용됩니다. 요컨데, 미리 어떤 paths를 Static Site Generation 할 지 정해두는 역할을 합니다.
  • <aside> ☝ 따로 설정을 하지 않는다면, next.js는 프로젝트를 빌드할 때 페이지를 Static Generation하려고 합니다.
728x90
Comments