새소식

반응형
WEB/Next.js

[Next.js] useEffect 와 getServersideprops 의 차이점

  • -
반응형

2023-04-13


사진: Unsplash 의 Arif Rasheed


1. useEffect

 

리액트를 기존에 사용해봤으면 해당 함수가 어떠한 기능을 수행하는지 알 수 있을 것이다. 해당 함수를 첫번째 매개 값으로는 수행할 함수를 받으며, 두번째 매개 값으로는 배열을 받는데 해당 배열에 있는 값이 변경될 경우에 첫번째의 있는 함수가 실행되게 된다. 여기서 useEffect의 비교 대상은 getServersideprops 이기 때문에 첫번째 매개 변수는 fetch 형태로 백엔드 서버에서 데이터를 가져오는 함수라고 가정해보자.

 

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.example.com/data');
      const json = await response.json();
      setData(json);
    }
    fetchData();
  }, []);

  if (!data) {
    return <div>Loading data...</div>;
  }

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  );
}

2. getServersideprops 

 

위의 코드를 getServersideprops 형식으로 변경하면 아래와 같은 코드가 된다. 가장 큰 차이점은 데이터를 가져오는 함수가 MyComponent에서 분리되어 선언된 것을 볼 수 있으며, useState 또한 제거된 것을 볼 수 있다. 또한 return 된 props 의 데이터가 MyComponent 매개 값으로 들어가는 것을 볼 수 있다. (참고로 getServersideprops 함수명은 고정이기 때문에 변경시 동작하지 않는다.)

 

You should use getServerSideProps only if you need to render a page whose data must be fetched at request time. (공식 문서에는 해당 함수는 페이지 요청에 있어 페이지 랜딩전에 데이터를 가져와야 할 경우에만 사용해야 한다고 나와 있다.)

 

import React from 'react';

function MyComponent({ data }) {
  if (!data) {
    return <div>Loading data...</div>;
  }

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  );
}

export async function getServerSideProps() {
  const response = await fetch('https://api.example.com/data');
  const json = await response.json();
  const data = json;

  return {
    props: { data }
  };
}

export default MyComponent;

https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

 

Data Fetching: getServerSideProps | Next.js

Fetch data on each request with `getServerSideProps`.

nextjs.org


3. 차이점

 

실제 코드상에 차이가 있는 것은 알았는데 동작에서는 어떤 차이가 있는지 알아보자. 우선 useEffect 로 가져온 데이터의 경우 현재 페이지의 컴포넌트들이 모두 마운트 된 후에 실행된다. 즉 페이지 로드 후 데이터를 가져온다. 반면에 getServersideprops 의 경우 먼저 데이터를 가져온 다음에 페이지가 로드 되기 때문에 두가지 함수는 정반대의 순서를 가지고 있다고 볼 수 있다.

https://blog.logrocket.com/wp-content/uploads/2022/02/next-getserversideprops-getstaticprops-diagram.png


4. 참고링크

https://www.reddit.com/r/nextjs/comments/giqryf/useeffect_and_serversideprops/

 

r/nextjs on Reddit: Useeffect and serversideprops

Posted by u/elguty_gabriel - 4 votes and 10 comments

www.reddit.com

https://blog.logrocket.com/getinitialprops-vs-getserversideprops-nextjs/

 

getInitialProps vs. getServerSideProps in Next.js - LogRocket Blog

Explore the differences between getInitialProps and getServerSideProps, two methods for defining props for server-side rendered pages.

blog.logrocket.com


메인 이미지 출처 : 사진: UnsplashArif Rasheed  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.