Next.js
Data
- 리액트에서는 데이터를 가져올 때 useEffect 안에서 가져오지만, next.js에서는 다른 방법을 사용한다.
- 사용 용도에 따라 방법이 나뉜다.
getStaticProps
- Static Generation으로 빌드할 때 데이터를 불러온다.
- getStaticProps 함수를 async로 export하면, 리턴되는 props를 가지고 페이지를 pre-render한다.
- build time에 페이지를 렌더링 한다.
- 사용시기
- 페이지를 렌더링하는 데 필요한 데이터는 사용자의 요청보다 먼저 build 시간에 필요한 데이터를 가져올 때 사용한다.
- 데이터를 공개적으로 캐시할 수 있을 때
- 페이지는 미리 렌더링돼야 하고(SEO의 경우), 매우 빨라야 할 때(성능을 위해 CDN에서 캐시할 수 있는 HTML 및 JSON 파일을 생성)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => {
<li>{post.title}</li>;
})}
</ul>
);
}
export async function getStaticPorps() {
const res = await fetch("http://localhost:3000/posts");
const posts = await res.json();
return {
props: {
posts,
},
};
}
getStaticPaths
- Static Generation으로 데이터에 기반하여 pre-render 시 특정한 동적 라우팅 구현(pages/post[id].js)
- 동적 라우팅이 필요할 때, 경로 리스트를 정의하고 HTML에 build 시간에 렌더링된다.
paths
- 어떠한 경로가 pre-render 될지를 결정한다.
- 만약 pages/posts/[id].js 이름의 페이지가 있다면 아래와 같이 작성하며, 빌드하는 동안 /posts/1과 /posts/2를 생성하게 된다.
1 2 3 4 5 6 7
return { paths: [ {params: {id: "1",}}, {params: {id: "2",}}, ], fallback: ... }
params
- 페이지의 이름이 pages/posts/[postid]/[commentId]라면, params는 postid와 commentid이다.
- 만약 페이지 이름이 pages/[…slug]와 같이 모든 경로를 사용한다면, params는 slug가 담긴 배열이어야 한다.[“postid”,”commentid”]
- fallback
- false라면 getStaticPaths로 리턴되지 않는 것은 모두 404 페이지가 뜬다.
- true라면 getStaticPaths로 리턴되지 않는 것은 404로 뜨지 않고 fallback 페이지가 뜨게 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export async function getStaticPaths() {
const res = await fetch("http://localhost:3000/posts");
const posts = await res.json();
const paths = posts.map((post) => ({
params: { id: posts.id },
}));
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const res = await fetch(`http://localhost:3000/posts/${params.id}`);
const post = await res.json();
return { props: { post } };
}
getServerSideProps
- Server Side Rendering으로 요청이 있을 때 데이터를 불러온다.
- 사용시기
- 요청할 때 데이터를 가져와야하는 페이지를 미리 렌더해야 할 때 사용한다.
- 서버가 모든 요청에 대한 결과를 계산하고, 추가 구성없이 CDN에 의해 결과를 캐시할 수 없기 때문에 첫 번째 바이트까지의 시간은 getStaticProps보다 느리다.
1
2
3
4
5
6
7
8
9
10
function Page({data}){
...
}
export async function getServerSideProps(){
const res = await fetch(".../data")
const data = await res.json();
return {props: {data}}
}