면접중 next.js에 관한 질문을 받았는데, 평소에 애매하게 알고 있던 부분이라서 명확하게 대답을 하지못했다. 따라서 다시 정리해본다. 🤓
Next 서버로 요청을 보냄 - 요청에 맞는 페이지 탐색 - _app.js 실행(getInitialProps가 있다면 실행) - _document.js 실행 - 컴포넌트 렌더링
이 때 _app.js와 _document.js는 가장 먼저 실행된다. 두 파일 모두 page 폴더에 위치 시킨다.
_app.js
Layout 컴포넌트 적용state유지 / ContextAPI의 Provider 사용import 'styles/reset.css';
import CartProvider from 'reducer/context';
import Layout from 'components/Layout/Layout';
function MyApp({ Component, pageProps }) {
  return (
    <CartProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </CartProvider>
  );
}
export default MyApp;
_document.js
head의 내용을 작성 (Google Font등)import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
  
  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}
export default MyDocument
getInitialProps enables server-side rendering in a page and allows you to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO.
Next.js에서는 getInitialProps이라는 비동기 함수를 사용해서 서버에서 미리 데이터를 fetching하고, 데이터가 담긴 페이지를 반환한다.
getInitialProps가 getStaticProps getServerSideProps getServerSideProps로 총 세가지로 세분화 되었다.getStaticProps와 getServerSideProps 의 차이점은, 빌드 이후 데이터의 변경 가능 여부가 다르다는 점이다.getStaticProps(Static Generation)
getServerSideProps(Server-side Rendering)
Next.js에서 styled-components를 사용하기 위해서 server side rendered styles을 에 injecting했는데, 현재는 createGlobalStyle를 _app.js에 사용하면 된다.