NextJS

Next - 주요 렌더링 패턴 4가지를 직접 구현해보기

jjangsh 2024. 9. 27. 01:18

Pre-Rendering (Static) - Server Side Generation (SSG)

// SSG - Server Side Generation(Static)
// 서버에서 미리 html을 만든 후 브라우저에 보여주는 렌더링
// 아무것도 하지 않으면 SSG
// next.js에서는 기본적으로 아무것도 설정하지 않았다면 SSG로 동작
// SSG는 빌드타임에 페이지를 만들어줌
// 정적 페이지를 로드하기 때문에 처음에 한번 로드하고 다시 로드하지 않음

const Ssg = async () => {
  const res = await fetch("http://localhost:4000/posts", {
    cache: "force-cache",
  });

  const data = await res.json();
  console.log(data); // 이 콘솔은 브라우저에 찍히지 않고 서버에 찍힘

  return <div>{JSON.stringify(data)}</div>;
};

export default Ssg;

 

 

Incremental Static Regeneration(ISR)

// ISR - Incremental Static Regeneration

const Isr = async () => {
  const res = await fetch("http://localhost:4000/posts", {
    next: {
      revalidate: 5,
    },
  });

  const data = await res.json();

  return <div>{JSON.stringify(data)}</div>;
};

export default Isr;

 

 

Pre-Rendering (Dynamic) - Server Side Rendering (SSR)

// SSR - Server Side Rendering(Dynamic)
// 사용자가 웹사이트에 접속시도를 할때마다 새롭게 렌더링

const Ssr = async () => {
  const res = await fetch("http://localhost:4000/posts", {
    cache: "no-store", // SSG랑 다른 부분
  });

  const data = await res.json();

  return <div>{JSON.stringify(data)}</div>;
};

export default Ssr;

 

 

Client Side Rendering(CSR) & use client

// CSR - Client Side Rendering
"use client";
import { useEffect, useState } from "react";

const Csr = () => {
  const [post, setPost] = useState("");

  useEffect(() => {
    fetch("http://localhost:4000/posts")
      .then((res) => res.json())
      .then((data) => {
        setPost(JSON.stringify(data));
      });
  });

  return <div>{post}</div>;
};

export default Csr;