새로고침을 하면 Style이 풀리는 현상을 만났습니다.
제 프로젝트는 next.js + react + styled-component를 사용하고있습니다.
왜 이런 현상이 일어날까요?
이유는 Next.js의 작동방식에 있습니다.
Next.js의 작동방식
사용자가 초기 페이지 접속 요청 시, 렌더링 될 html을 보냅니다.
우선적으로 HTML을 보여줍니다.
이후 script파일을 받아 화면을 실행시켜줍니다.
여기서 주의점은 styled-component는 CSS in JS 형식이기 때문에 html파일을 보여줄 때 style이 적용되지 않는 상태로 화면이 보여집니다.
우선 next.config.js파일에 styledComponents설정을 해줍니다.
const nextConfig = {
...
compiler: {
styledComponents: {
ssr: true,
}
},
...
}
이후 13버전 이전에 app폴더에 사용되어왔던 _app.tsx, _documents.tsx를 더이상 사용하지 않습니다.
registry.tsx를 생성한 후 레지스트리에 수집되어 root레이아웃에 <head>
태그를 삽입해주는 useServerInsertedHTML훅을 사용하여 client component를 생성해줍니다.
root layout에 children를 style registry component로 감싸서 해결합니다.
https://nextjs.org/docs/architecture/nextjs-compiler#styled-components
https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components