[Next.js] getStaticProps vs getServerSideProps (영상 확인)

하태현·2021년 4월 20일
2

우선은 두 함수 모두 pre-render가 필요한 경우(SEO, AdSense 등)에만 사용하도록 권장한다.


getStaticProps

"빌드 시에 딱 한번만" 호출되고, 바로 static file로 빌드 된다.
(HTML과 getStaticProps의 실행 결과가 담긴 JSON 파일을 생성한다.)

const Counter = () => {
  return (...)
}

export const getStaticProps: GetStaticProps = wrapper.getStaticProps(async ({ store, locale }) => {
  if (store.getState().sampledata) {
    store.dispatch(loadData())
    store.dispatch(END)
  }
  await store.sagaTask?.toPromise()
  
  return {
    props: {
      ...(await serverSideTranslations(locale, ['counter', 'header', 'userlist'])),
    },
  }
})

counter의 getStaticProps에서 redux store에 user data를 업데이트 하는 함수를 실행하고 있다.

빌드시 고정되는 값으로, 빌드이후에는 변경이 불가합니다.

앱 빌드 후에 바뀌지 않는 내용이 있는 Page에서 사용하는 것이 좋다.
호출 시 마다 매번 data fetch를 하지 않으니 getServerSideProps 보다 성능 면에서 좋다.

소스코드

function Blog({ posts, rand }) {
  return (
    <>
      <h1>{rand}</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.name}</li>
        ))}
      </ul>
      <Link href="/">
        <a className="nav-link">뒤로가기</a>
      </Link>
    </>
  )
}

export const getStaticProps: GetStaticProps = async () => {
  const rand = Math.floor(Math.random() * 10)
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const posts = await res.json()

  return {
    props: {
      posts,
      rand,
    },
  }
}

export default Blog

언제 getStaticProps 쓰나?

  • SEO 가 필요하고 변하지 않는 공개적인 캐시 데이터를 가져올 필요가 있을 때

    e.g. 마케팅 페이지, 블로그 포스트, 제품 목록, 도움말 및 문서 등

getStaticPaths

getStaticPaths 는 동적 라우팅 페이지에서 getStaticProps 를 사용할 때 함께 사용한다. (getServerSideProps 와는 함께 사용할수 없다.)


getServerSideProps

"Page가 요청받을 때 마다" 호출되어 pre-rendering 한다.

Pre-render가 꼭 필요한 동적 데이터가 있는 Page에서만 사용하자.

매 요청 마다 호출 되므로 성능은 getStaticProps보다 뒤지지만, 내용을 언제든 동적으로 수정이 가능하다.

소스코드

function Blog({ posts, rand }) {
  return (
    <>
      <h1>{rand}</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.name}</li>
        ))}
      </ul>
      <Link href="/">
        <a className="nav-link">뒤로가기</a>
      </Link>
    </>
  )
}

export const getServerSideProps: GetServerSideProps = async () => {
  const rand = Math.floor(Math.random() * 10)
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const posts = await res.json()

  return {
    props: {
      posts,
      rand,
    },
  }
}

언제 getServerSideProps 쓰나?

  • 요청 시 데이터를 가져와야 하는 페이지를 사전 렌더링 해야 하는 경우에만
  • 데이터를 미리 렌더링 할 필요가 없다면 Client-Side에서 데이터 페칭을 고려해 봐야 한다.

차이점

두 영상을 보시면 getStaticProps 사용 시 최초 한번 rand가 2로 고정이 되어서 이후 해당 페이지를 다시 방문 하여도 rand가 변하지 않는다.

getServersideProps 사용 시 해당 페이지 방문 시 마다 rand가 변경 되는 모습을 볼수 있다.

getStaticProps와 getServerSideProps은 별 차이가 없어 보이지만, 빌드 이후 변경가능 여부가 있으니 주의해서 사용하자.

소스코드

https://github.com/HTHstudy/nextjs-typescript-redux-saga-i18next
코드를 실행 하면서 테스트 해보고 싶으신 분들을 위한 링크 입니다.

profile
왜?를 생각하며 개발하기, 다양한 프로젝트를 경험하는 것 또한 중요하지만 내가 사용하는 기술이 어떤 배경과 이유에서 만들어진 건지, 코드를 작성할 때에도 이게 최선의 방법인지를 끊임없이 질문하고 고민하자. 이 과정은 앞으로 개발자로 커리어를 쌓아 나갈 때 중요한 발판이 될 것이다.

0개의 댓글