Next.js 페이지와 렌더링 방법

한칙촉·2023년 8월 10일

Next.js

목록 보기
3/4

1. Next.js의 페이지와 데이터 취득

종류데이터 취득에 사용하는
주요 함수
데이터 취득 시점보충 설명
SSGgetStaticProps빌드 시 (SSG)데이터 취득을 전혀 수행하지 않는 경우도 SSG에 해당
SSRgetServerSideProps사용자 요청 시 (서버 사이드)getInitialProps를 사용해도 SSR
ISRrevalidate를 반환하는 getStaticProps빌드 시 (ISR)ISR은 배포 후에도 백그라운드 빌드가 실행됨
CSR그 밖의 임의의 함수사용자 요청 시 (브라우저)CSR은 SSG/SSR/ISR과 동시에 사용 가능

+) revalidate = 페이지의 유효 기간을 초로 나타낸 것


2. SSG를 통한 페이지 구현

import { NextPage } from "next";
import Head from "next/head";

type SSGProps = {};

const SSG: NextPage<SSGProps> = () => {
  return (
    <div>
      <Head>
        <title>Static Site Generation</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <p>이 페이지는 정적 사이트 생성을 통해 빌드 시 생성된 페이지입니다</p>
      </main>
    </div>
  );
};

export default SSG;

NextPage = pages를 위한 타입
받을 props 결정 -> NextPage< Props >와 같이 지정


3. getStaticProps를 사용한 SSG를 통한 페이지 구현

import { NextPage, GetStaticProps, NextPageContext } from "next";
import Head from "next/head";

type SSGProps = {
  message: string;
};

const SSG: NextPage<SSGProps> = (props) => {
  const { message } = props;

  return (
    <div>
      <Head>
        <title>Static Site Generation</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <p>이 페이지는 정적 사이트 생성을 통해 빌드 시 생성된 페이지입니다</p>
        <p>{message}</p>
      </main>
    </div>
  );
};

export const getStaticProps: GetStaticProps<SSGProps> = async (context) => {
  const timestamp = new Date().toLocaleString();
  const message = `${timestamp}에 getStaticProps가 실행됐습니다`;
  console.log(message);

  return {
    props: {
      message,
    },
  };
};

export default SSG;

4. SSR을 통한 페이지 구현

import { GetServerSideProps, NextPage } from "next";
import Head from 'next/head';

type SSRProps = {
    message: string;
  };
  
  const SSR: NextPage<SSRProps> = (props) => {
    const { message } = props;
  
    return (
      <div>
        <Head>
          <title>Create Next App</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>
        <main>
          <p>이 페이지는 서버 사이드 렌더링을 통해 접근 시에 서버에서 그려진 페이지입니다</p>
          <p>{message}</p>
        </main>
      </div>
    );
  };
  
  export const getStaticProps: GetServerSideProps<SSRProps> = async (context) => {
    const timestamp = new Date().toLocaleString();
    const message = `${timestamp}에 getServerSideProps가 실행됐습니다`;
    console.log(message);
  
    return {
      props: {
        message,
      },
    };
  };
  
  export default SSR;
  

5. ISR을 통한 페이지 구현

import { NextPage, GetStaticProps } from "next";
import Head from "next/head";
import { useRouter } from "next/router"

type ISRProps = {
  message: string;
};

const ISR: NextPage<ISRProps> = (props) => {
  const { message } = props;
  const router = useRouter();

  if (router.isFallback) {
    // 폴백용 페이지 반환
    return <div>Loading...</div>;
  }

  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <p>이 페이지는 ISR을 통해 빌드 시 생성된 페이지입니다.</p>
        <p>{message}</p>
      </main>
    </div>
  );
};

export const getStaticProps: GetStaticProps<ISRProps> = async (context) => {
  const timestamp = new Date().toLocaleDateString();
  const message = `${timestamp}에 이 페이지의 getStaticProps가 실행됐습니다.`;

  return {
    props: {
      message,
    },
    revalidate: 60, // 페이지의 유효 기간을 초 단위로 지정
  };
};

export default ISR;

가장 처음으로 페이지에 접근한 경우
-> 폴백 페이지 표시됨, 서버 측에서 실행한 getStaticProps를 기반으로 클라이언트에서 다시 화면 그림

그 이후의 요청에 대해서는 revalidate에서 지정한 시간 내에는 서버 사이드에서 그려서 저장하고 있던 페이지를 반환

유효 기간이 지난 뒤 요청이 있는 경우, 해당 요청에 대해서는 현재 저장돼 있는 페이지를 반환 -> getStaticProps를 실행하고 페이지를 그려 새로운 캐시로 저장

profile
빙글빙글돌아가는..

1개의 댓글

comment-user-thumbnail
2023년 8월 10일

감사합니다. 이런 정보를 나눠주셔서 좋아요.

답글 달기