wherehows / yhkim.dev

https://www.yhkim.dev
BSD Zero Clause License
0 stars 0 forks source link

fix: 다크모드 토글 관련 SSR 이슈 해결 #110

Closed wherehows closed 1 year ago

wherehows commented 1 year ago

Hydration Matching Error

// 🟢 1번 상황
const Layout = Component => props => {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  if (!isMounted) {
    return (
      <div
        style={{
          visibility: 'hidden',
        }}
      >
        <Component {...props} />
      </div>
    );
  }

  return <Component {...props} />;
};

// 🔴 2번 상황
const Layout = Component => props => {
  if (typeof window === 'undefined') {
    return (
      <div
        style={{
          visibility: 'hidden',
        }}
      >
        <Component {...props} />
      </div>
    );
  }

  return <Component {...props} />;
};

gatsby-ssr.js 관련

  1. 아래 내용은 nextjs에서 getStaticProps 할때 html에 데이터가 포함되어 내려오는 상황과 유사한듯. image

https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/#onRenderBody

  1. default-html.js는 nextjs에서 봐왔던 document와 동일

https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/cache-dir/default-html.js

  1. gatsby-ssr.js가 제대로 실행되지 않는 이슈 여지껏 제대로 실행 안되고 있었음. https://stackoverflow.com/questions/67909219/in-what-circumstances-is-onrenderbody-not-run

다크 모드 관련

  1. :root.dark 와 :root .dark :root.dark의 경우, :root의 클래스명이 dark인 경우, :root .dark의 경우, 하위 요소 중 클래스명이 dark인 경우

  2. gatsby-ssr.js에서 document.body.className으로 접근이 불가능한 이유 아래에서 1번 코드는 정상적으로 동작하지만, 2번 코드는 정상적으로 동작하지 않는다. body가 파싱되기 전에 body에 접근하고 있기 때문

    
    // 🟢 1번 코드
                  if (theme === 'dark') {
                    document.documentElement.className = 'dark';
                  } else {
                    document.documentElement.className = 'light';
                  }

// 🔴 2번 코드 if (theme === 'dark') { document.body.className = 'dark'; } else { document.body.className = 'light'; }

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
blog-renewal ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 9, 2023 2:34pm