Next.js Pre-rendering and Data Fetching

Tony·2021년 11월 9일
0

react

목록 보기
32/82

Next.js version 12 업데이트 후 .server.js로 페이지 컴포넌트를 만들면 getServerSideProps, getStaticProps 둘다 필요없다고 하는 것 같은데 이것을 실험해보기 전에 getServerSideProps을 먼저 사용해봐야겠다는 생각이 들었다.

이번에 나현님의 PR에서 router에 shallow 옵션을 줄 수 있다는 것을 알게 됐는데 이것과 같이 사용해보려 한다.

Pre-rendering and Data Fetching

Two Forms of Pre-rendering

  • Static Generation : getStaticProps




  • Server-side Rendering : getServerSideProps

getStaticProps와 getServerSideProps in next.js

구버전 next에서는 data fetching을 getInitialProps으로 진행했는데, 9.3부터는 getStaticProps, getStaticPaths, getServerSideProps으로 나뉩니다.

getStaticProps

  • 빌드시 고정되는 값으로, 빌드이후에는 변경이 불가합니다.
// **************************************** e.g.1,
export default function Home(props) { ... }

export async function getStaticProps() {
  // Get external data from the file system, API, DB, etc.
  const data = ...

  // The value of the `props` key will be
  //  passed to the `Home` component
  return {
    props: ...
  }
}
  
// **************************************** e.g.2,
function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

export async function getStaticProps() {
  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

getServerSideProps

  • 빌드와 상관없이, 매 요청마다 데이터를 서버로부터 가져옵니다.

적용

  • useEffect에서 dispatch를 이용해서 reqeust action을 보내는 것을 getServerSideProps을 이용하려고 했으나 hooks rule에 위배(hook은 컴포넌트 안에서 사용해야 함)
  • 실험 불가

참고

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

0개의 댓글