티스토리 뷰

https://nextjs.org/docs/basic-features/data-fetching/get-server-side-propsNext.js에서 데이터를 가져올 때 사용하는 방식 중 getServerSideProps와 getStaticProps를 TypeScript로 작성한 예제 코드를 찾기 힘들어 간단히 정리해보았습니다.

getStaticProps

빌드 시(npm run build) 한 번만 호출되기 때문에 빌드 후 바뀌지 않는 내용이 있는 페이지에서 사용하면 됩니다. 당연히 빌드시 한 번 호출되고 정적 파일로 생성되기 때문에 getServerSideProps와 비교해서 성능에서 우월합니다.

예제 코드

import { GetStaticProps, InferGetStaticPropsType } from "next"

type Props = {
  store_id: number
}

export default ({ store_id }: InferGetStaticPropsType<typeof getStaticProps>) => {
  return // ...
}

export const getStaticProps: GetStaticProps<Props> = async (context) => {
  const store_id = 1

  return {
    props: { store_id }
  }
}

getServerSideProps

getStaticProps와 다르게 페이지를 불러올 때마다 호출되기 때문에 빌드 후에도 바뀌는 동적인 내용을 담고 있는 페이지에서사용합니다. 페이지를 불러올 때마다 호출되기 때문에 getServerSideProps와 비교해서 성능에서는 떨어집니다. 꼭 필요한 경우에만 사용하고, 페이지에서 자주 업데이트되는 내용이 포함되어 있을 경우 client side에서 useEffect 등을 이용하여 호출을 하는 것을 권장합니다.

예제 코드

import { GetServerSideProps, InferGetServerSidePropsType } from 'next'

type Props = {
  students: student[]
}

export default ({ students }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
  return // ...
}

export const getServerSideProps: GetServerSideProps<Props> = async (context) => {
  const res = await fetch(`https://.../students`)
  const t_orders: t_order[] = await res.json()

  return {
    props: { students }
  }
}

참고 문서

최근에 올라온 글
최근에 달린 댓글
글 보관함
Total
Today
Yesterday