우선은 두 함수 모두 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
쓰나?두 영상을 보시면 getStaticProps 사용 시 최초 한번 rand가 2로 고정이 되어서 이후 해당 페이지를 다시 방문 하여도 rand가 변하지 않는다.
getServersideProps 사용 시 해당 페이지 방문 시 마다 rand가 변경 되는 모습을 볼수 있다.
getStaticProps와 getServerSideProps은 별 차이가 없어 보이지만, 빌드 이후 변경가능 여부가 있으니 주의해서 사용하자.
https://github.com/HTHstudy/nextjs-typescript-redux-saga-i18next
코드를 실행 하면서 테스트 해보고 싶으신 분들을 위한 링크 입니다.