styled-components를 사용하여 theme을 설정했는데 새로고침을 할 때 마다 깜빡 거리게 된다.
이유를 자세히 완벽히는 알지 못하지만 react가 랜더링 할 때까지의 틈을타서 html이 보이기 때문이라고 하는데 그 현상을 막고 싶었다.
새로 고침 또는 새로 접속할 때마다 깜빡거리기 때문에 아주 거슬린다.
찾아보다 보니 index.html에서 해결 할 수 있다고 한다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="text/javascript">
(function() {
function getInitialColorMode() {
const isClient = typeof window !== 'undefined';
if (isClient) {
const persistedColorPreference = JSON.parse(window.localStorage.getItem('todo_theme'));
if (persistedColorPreference) {
return persistedColorPreference;
}
const systemPreference = window.matchMedia('(prefers-color-scheme: dark)');
if (systemPreference.matches) {
return 'darkTheme';
}
return 'lightTheme';
}
}
const colorMode = getInitialColorMode();
document.documentElement.style.setProperty(
'background-color',
colorMode === 'lightTheme' ? '#dcdde1' : '#2f3640'
);
document.documentElement.style.setProperty(
'color',
colorMode === 'lightTheme' ? '#2f3640' : '#dcdde1'
);
})();
</script>
<title>TS ToDos</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
위와 같이 index.html가 로딩이 될 때 즉시실행 함수를 사용하여 client가 현재 window인지 체크 후 window라면 localStorage에 있는 theme 값을 가져온다.
만약 localStorage에 값이 없다면 사용자의 system의 기본 테마를 참조하여 그에 맞는 theme을 return한다.
그리고 return 받은 theme을 가지고 그에 맞는 색을 배경색과 font 색정도만 세팅한다.
그러면 새로 고침 하더라도 깜빡거림 현상이 사라진다.
한번 적용을 해 봤으니 두번 세번은 어렵지 안겠지..