next에서 styled-components를 사용하면 css 로딩이 늦게 되어서 깜박이는 현상이 발생한다.
따라서 _document파일에 css를 미리 적용해야한다. _document 파일은 Pages폴더 내부에 존재하는 모든 페이지에 global한 설정값을 줄 수 있는 파일이다.
공식문서를 참고하여 다음과 같이 입력해주면 된다.
import Document from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(
<>
<App {...props} />
</>
),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}