[Next.js] getStaticProps vs. getServerSideProps

Tony·2021년 11월 12일
0

react

목록 보기
35/82

getStaticProps vs. getServerSideProps

getStaticProps

"빌드 시에 딱 한 번"만 호출되고, 바로 static file로 빌드됩니다. 따라서, 이후 수정이 불가능합니다.
SSG (Static Site Generation) 개념입니다.

getServerSideProps

"page가 요청받을때마다" 호출되어 pre-rendering합니다.
SSR (Server Side Rendering) 개념입니다.
pre-render가 꼭 필요한 동적 데이터가 있는 page에 사용하면 됩니다.
매 요청마다 호출되므로 성능은 getStaticProps에 뒤지지만, 내용을 언제든 동적으로 수정이 가능합니다.

// getStaticProp()에 의해 빌드시에 게시물이 채워집니다.
function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

export async function getStaticProps() {
  // 외부 API endpoint로 Call 하여 Post 정보를 가져옵니다.
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // posts 데이터가 담긴 prop를 빌드시간에 Blog 컴포넌트에 전달합니다.
  return {
    props: {
      posts,
    },
  }
}

export default Blog

고찰

  • getServerSideProps에선 hooks를 사용할 수 없다.
    fetch를 사용해서 데이터를 가져온 뒤 props를 return 한 것을 컴포넌트에서 가져오는 방식으로 사용해야 될 것 같다.
  • 리덕스를 사용하지 않아서 비지니스 로직을 모두 리덕스에 담을 수 없는 점은 아쉬운 것 같다.
  • React 18버전이 정식 출시되고 다른 라이브러리들의 dependencies에서 React18이 추가가 된다면 Next.js 12의 React Server Components를 이용해서 테스트해보고 싶다.

참고

profile
움직이는 만큼 행복해진다

0개의 댓글