[javascript] Next.js에서의 데이터 fetching 방법들은 어떤 것이 있나요?
  1. 정적 생성 (Static Generation) - getStaticProps
    • getStaticProps 함수를 사용하여 페이지가 빌드되기 전에 미리 데이터를 가져올 수 있습니다.
    • 주로 정적인 데이터 또는 외부 API로부터 변경이 드물게 발생하는 데이터를 가져올 때 사용됩니다.
    • 예시:
      export async function getStaticProps() {
        const res = await fetch('https://api.example.com/data');
        const data = await res.json();
           
        return {
          props: {
            data
          }
        };
      }
      
  2. 서버 사이드 렌더링 (Server Side Rendering) - getServerSideProps
    • getServerSideProps 함수를 사용하여 매 요청마다 데이터를 가져올 수 있습니다.
    • 주로 동적인 데이터를 가져와야 할 때 사용됩니다.
    • 예시:
      export async function getServerSideProps(context) {
        const res = await fetch(`https://api.example.com/data/${context.params.id}`);
        const data = await res.json();
           
        return {
          props: {
            data
          }
        };
      }
      
  3. 클라이언트 사이드 렌더링 (Client Side Rendering) - SWR 라이브러리
    • swr 라이브러리를 사용하여 클라이언트 측에서 데이터를 가져올 수 있습니다.
    • 주로 동적인 데이터를 가져와야 할 때 사용되며, 서버 측에서는 기존 데이터를 제공합니다.
    • 예시:
      import useSWR from 'swr';
           
      function MyComponent() {
        const { data, error } = useSWR('https://api.example.com/data', fetcher);
           
        if (error) return <div>오류가 발생했습니다.</div>;
        if (!data) return <div>데이터를 불러오는 중입니다...</div>;
           
        return <div>{data}</div>;
      }
      

Next.js에서는 다양한 데이터 fetching 방법을 사용할 수 있으며, 프로젝트의 요구사항에 따라 적절한 방법을 선택할 수 있습니다. 추가로 API 요청에 관련된 설정이 필요한 경우, axios, fetch 등의 라이브러리를 함께 사용할 수도 있습니다.

더 자세한 내용은 Next.js 공식 문서를 참고하시기 바랍니다.