Next.js 에서 Antd 사용 시 Warning 해결

Antd를 이용하다 보면

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.
    at Overflow (/home/benjie/Dev/graphile/starter/node_modules/rc-overflow/lib/Overflow.js:42:32)
    at InheritableContextProvider (/home/benjie/Dev/graphile/starter/node_modules/rc-menu/lib/context/MenuContext.js:39:23)
~~~~

심심치 않게 위와 같은 경고가 발생한다.

경고이기도 하고 계속 찾아봐도 Antd 라이브러리의 문제고 실제로 별 문제가 없으니 무시하라고 하는 글이 상당히 많았지만 거슬리기 때문에 해결법을 계속 찾아보았다.

useLayoutEffect와 SSR의 문제로 보이는데
React.useLayoutEffect = React.useEffect;
위와 같이 오버라이딩? 해버리면 경고가 사라진다고 한다.

Next.js의 SSR은
_app.js->_document.js->요청페이지->_app.js->요청페이지
순서로 실행되는데
앞에 3개는 서버사이드에서 요청이나 데이터패칭 등을 처리하기 위한 getInitialProps, getStaticProps 등의 함수를 찾아서 실행하는 과정이고
이후 2개는 클라이언트에 전달해서 렌더하는 과정이다.

경고 해결을 위해 깃허브에서 본 해결법은 _document.js 페이지에 React.useLayoutEffect = React.useEffect; 요걸 넣어주면 해결된다고 한다.

근데 이 파일은 서버에서 실행되는 것이고 기본적으로 제공되는건 아니다. 커스터마이징을 위해 사용하려면 파일이름을 동일하게 작성하고 그 안에 입력을 해야한다.
별다른 동작의 변화 없이 위 명령어만 추가하는 것을 입력하면 된다.

_document.js의 동작원리나 기본적으로 작성되어 있어야 하는 내용같은건 잘 몰라서 그냥 복붙했다.

코드는 다음과 같다.


// _document.js

import Document, {
  Html,
  DocumentContext,
  Head,
  Main,
  NextScript,
} from 'next/document';

import React from 'react';

React.useLayoutEffect = React.useEffect;

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head></Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

이제 경고 없이 잘 동작한다...

참조 깃허브 링크
Next.js SSR순서 참조 링크

좋은 웹페이지 즐겨찾기