😎 알게된것
Next.js의 Page 렌더링 방식
1. Pre-Rendering
- 더 나은 성능, SEO를 위해 넥스트는 page를 위한 HTML을 사전에 만드는 것을 원칙으로 한다.
- 언제 HTML를 만드느냐에 따라 다음 두가지로 나뉜다.
- Static Generation :
build
할 때 생성 (product ver 에서는 next build
하면 생성됨) 해서 request 때마다 재사용
- Server Side Rendering :
request
할 때마다 각각 생성
- next는 Static Generation을 권장하고있다. 유저의 요청에 앞서서 페이지가 렌더링 되어야 하는가? 라고 자문했을때 yes 라면 Static Generation을 권장!
2. Static Generation
2-1. Without Data
2-2. With Data
getStaticProps
: page content가 외부 data에 의존할 때 사용
- build 때 호출됨
- 이런식으로 return 해주며,
props.posts
로 컴포넌트에서 props로 받을 수 있음
function Blog({ posts }) {
}
export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default Blog
getStaticPaths
: page 경로가 외부 data에 의존할 때 사용 (dynamic routing)
- pages/posts/[id] 이런 경우에 사용
export async function getStaticPaths() {
const res = await fetch('https://.../posts')
const posts = await res.json()
const paths = posts.map((post) => ({
params: { id: post.id },
}))
return { paths, fallback: false }
}
3. SSR
getServerSideProps
사용
- 위 두 함수와 유사하지만, 차이점은 얘는 build 때 호출 되는게 아니라, 유저의 request 때마다 매번 호출된다.
function Page({ data }) {
}
export async function getServerSideProps() {
const res = await fetch(`https://.../data`)
const data = await res.json()
return { props: { data } }
}
export default Page
Reference