목차
1. Next.js에서 styled components 사용 시 깜빡이는 현상
환경
Next 14.0.4
styled-components 6.1.6
프로젝트를 진행하면서 Next.js와 styled components를 사용할 때 아래와 같이 깜빡임이 발생했다.
깜빡임이 발생하는 이유
styled-components는 CSS in JS로, JS안에 CSS를 작성하는 것을 의미한다.
Next.js는 SSR(Server Side Rendering)로 Hydrate 과정에서 다운로드 받은 JS를 통해 지정된 스타일 정보가 생기기 때문에 페이지 로드 시 스타일이 잠깐 누락되어 깜빡이는 현상이 발생한다.
Hydrate ? Server Side 단에서 렌더링 된 정적 페이지와 번들링된 JS파일을 클라이언트에게 보낸 뒤, 클라이언트 단에서 HTML 코드와 React인 JS코드를 서로 매칭 시키는 과정
2. styled components 설치
npm i styled-components
2. styled components SSR 설정
2-1. lib/registry.tsx 파일 생성
'use client'
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
export default function StyledComponentsRegistry({
children,
}: {
children: React.ReactNode
}) {
const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
useServerInsertedHTML(() => {
const styles = styledComponentsStyleSheet.getStyleElement()
styledComponentsStyleSheet.instance.clearTag()
return <>{styles}</>
})
if (typeof window !== 'undefined') return <>{children}</>
return (
<StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
{children}
</StyleSheetManager>
)
}
2-2. app/layout.tsx 래핑
import StyledComponentsRegistry from '../lib/registry'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>
<StyledComponentsRegistry>{children}</StyledComponentsRegistry>
</body>
</html>
)
}
2-3. next.config.js에서 스타일 구성 요소 활성화
module.exports = {
compiler: {
styledComponents: true,
},
}
깜빡임 해결 완료!
reference
Hydrate
https://helloinyong.tistory.com/315
Next.js의 Hydrate란?
Next.js 프레임워크의 동작원리를 제대로 파악하고 있는 개발자라면 Hydrate에 대해선 이미 익숙한 용어일 것이다. 그러나 Next.js의 주요 동작 방식 중 하나임에도, 눈에 잘 띄지 않아 놓치기도 쉬운
helloinyong.tistory.com
CSS-in-JS
https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components
Styling: CSS-in-JS | Next.js
Use CSS-in-JS libraries with Next.js
nextjs.org
'Next' 카테고리의 다른 글
[Next] ReferenceError: window is not defined (0) | 2024.02.14 |
---|---|
[Next] Next+styled components에서 SVG 커스텀하기 (0) | 2024.01.08 |
[Next] next.js 13 초기 세팅 (0) | 2023.10.13 |
댓글