
Codefug Blog

CSR SSG SSR
React 공식 문서에는 다음과 같은 문장이 있습니다.
The library for web and native user interfaces
React는 웹과 UI를 위한 라이브러리이지 프레임워크가 아닙니다.
Library : 구체적이고 잘 정의된 일련의 작업 수행, 메서드를 호출하면 제어권을 갖게 된다.
Framework : 애플리케이션이 스켈레톤을 채워 작업 내용을 정의, 프레임워크가 우리를 호출한다.
React Fiber Architecture를 이용해 리렌더링을 최적화하는 등 복잡한 내부 로직을 가지고 있습니다.
하지만 결국 UI를 돕기 위한 라이브러리입니다.
자유도가 높아 다양한 패키지를 사용해 라우팅 같은 기능을 추가할 수 있었습니다.
하지만 복잡해지는 웹 기술에서는 정형화된 프레임워크가 필요했습니다.
이런 요구에 맞춰 React를 활용한 프레임워크 Next.js가 등장했습니다.
Next.js 공식 문서에는 다음 문구가 있습니다.
The React Frame Work for the Web
next/head를 이용한 메타데이터 삽입, app router와 pages router를 이용한 라우팅, Image 컴포넌트의 lazy loading 등 다양한 기능이 있습니다.
Next.js의 가장 큰 특징은 렌더링 방식입니다.
Server-Side-Rendering
모든 요청마다 서버에서 HTML 페이지를 생성합니다.
Next.js에서 getServerSideProps 함수로 구현됩니다.
모든 요청마다 서버에서 해당 함수가 실행됩니다.
클라이언트에서 나머지 JavaScript를 적용하는 과정을 hydration이라고 합니다.
자주 업데이트되는 데이터를 pre-render할 때 유용합니다.
Static Site Generation
빌드 시간에 서버가 HTML을 생성하고 모든 요청에서 재사용합니다.
데이터를 fetching하지 않으면 Next.js는 자동으로 SSG 방식을 사용합니다.
Next.js 공식 문서는 두 가지 사용 상황을 제시합니다.
export default function Blog({ posts }) {
// Render posts...
}
// This function gets called at build time
export async function getStaticProps() {
// Call an external API endpoint to get posts
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,
},
};
}
getStaticProps 안에서 fetch로 데이터를 가져와 빌드 타임에 posts prop으로 전달합니다.
Next.js의 Dynamic Routes를 이용한 경우입니다.
// This function gets called at build time
export async function getStaticPaths() {
// Call an external API endpoint to get posts
const res = await fetch("https://.../posts");
const posts = await res.json();
// Get the paths we want to pre-render based on posts
const paths = posts.map((post) => ({
params: { id: post.id },
}));
// We'll pre-render only these paths at build time.
// { fallback: false } means other routes should 404.
return { paths, fallback: false };
}
pages/posts/[id].js 형태로 Dynamic Routes를 구성한 경우 fetch로 id에 들어갈 전체 데이터를 가져옵니다.
params에 key-value 형태로 저장됩니다.
export default function Post({ post }) {
// Render post...
}
export async function getStaticPaths() {
// ...
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`);
const post = await res.json();
// Pass post data to the page via props
return { props: { post } };
}
데이터는 getStaticProps의 인자가 되어 정적 페이지 최적화에 사용됩니다.
getStaticProps는 서버에서 실행되므로 CORS 문제가 발생하지 않습니다.
export const getStaticProps = (async (context) => {
const likeRes = await fetch(`${BASE_URL}/articles?pageSize=3&&orderBy=like`);
const likeData: ArticleData = await likeRes.json();
const likeList = likeData.list ?? [];
return { props: { likeList } };
}) satisfies GetStaticProps<{
likeList: Article[] | [];
}>;
프로젝트에서 사용했던 코드의 일부입니다.
Best 게시물 3개를 화면에 표시하는 작업이었습니다.
데이터를 유동적으로 변경할 필요가 없어 SSG를 사용하여 렌더링을 최적화했습니다.
Incremental Static Regeneration
사이트 구축 후에도 정적 페이지를 생성하거나 업데이트하는 방식입니다.
전체 사이트를 재구축할 필요 없이 페이지별로 정적 생성을 사용할 수 있습니다.
getStaticProps에 revalidate props를 추가하면 사용할 수 있습니다.
geeksforgeeks
Next 공식문서Modern React Deep dive - 김용찬
Next.js 웹사이트 만들기 - 코드잇
Devlane Blog
haszankauna Post
잘못된 내용이 있다면 댓글로 알려주세요. 감사합니다.