Skip to content

useColorMode() cannot safely be used with SSR #9629

Closed as not planned
Closed as not planned

Description

@NickGerleman

Have you read the Contributing Guidelines on issues?

Prerequisites

Description

I have a website which relies on the usePrismTheme() hook, relying on useColorMode(). The website has an interactive code example (very similar in both form and code to the one provided by Docusaurus itself).

The site is dark mode by default, but may be set to light mode. When I start the website, after previously setting light mode, everything looks corect when I start via development server, but if I do a build, the code relying on the usePrismTheme() hook shows the incorrect theme.

image image

When I debugged this, it looks like:

  1. Docusaurus SSR generates the page using a color mode of "dark"
  2. useColorMode, from first client render, has a color mode of "light"
  3. Hydration succeeds, even though the prism styles are mismatched?
  4. We're in a weird hybrid state where the color is incorrect until the theme is changed again

I found Docusaurus itself has a hack to get around this: https://github.com/facebook/docusaurus/blob/61116e2ad6f675d0ba1abef98484712b14834bdb/packages/docusaurus-theme-live-codeblock/src/theme/Playground/index.tsx#L78

But this causes a black to white (or white to black) flash during hydration which is pretty jarring if the UI is shown above the fold.

This seems like a more general issue, where anything relying on the hook might get a different value at client time compared to server time. Though I'm not exactly sure how this could be cleanly solved without doing SSR on both sets of color modes.

Reproducible demo

https://github.com/facebook/yoga/tree/main/website-next

Steps to reproduce

  1. yarn start (works correctly)
  2. yarn build (does not show correctly)

Expected behavior

Light mode should use light scheme in prism editor

Actual behavior

Shows dark theme

Your environment

Self-service

  • I'd be willing to fix this bug myself.

Activity

  1. added
    bug
    status: needs triage
    on Dec 14, 2023
  2. NickGerleman commented on Dec 14, 2023

    @NickGerleman
    ContributorAuthor

    Oh I probably should have searched before I made this. Looks like #7986 is effectively the same thing.

  3. NickGerleman commented on Dec 14, 2023

    @NickGerleman
    ContributorAuthor

    For this specific case of issue of code highlighting, I bet I could make a custom prism theme that uses variables set by style with html data theme selector like other responsive UI does.

  4. slorber commented on Dec 14, 2023

    @slorber
    Collaborator

    Yes this is a known issue.

    At build time we have to pick one color mode to render the static pages, and cannot read OS settings or localStorage there so we have to pick one or another.

    At hydration time we should hydrate with the exact same color that was used at build time (I don't think we do this correctly atm), and only then update the color in React state to match the actual rendered value.

    We inline critical JS in the page to render the correct color mode through CSS selectors, before the hydration, this is what prevents our theme to have a flash. Unfortunately, React has to see the real color mode a bit later, after hydration happens.

    My recommendations would be:

    • Prefer CSS selectors for theming ([data-theme='dark'] { ... }) to avoid flashes
    • Reduce usage of useColorMode() to limited use-cases, like a color mode toggle button

    Regarding the prism code block fouc, we'd also want to use CSS variables for this. See FormidableLabs/prism-react-renderer#149

    I guess one issue is enough, so let's close in favor of the existing one: #7986

  5. added
    closed: duplicate
    and removed
    status: needs triage
    on Dec 14, 2023
  6. finom commented on Dec 29, 2023

    @finom

    I've solved this problem by using useEffect and localStorage. In my case I needed to invert an image but you can call any other function.

    const { colorMode } = useColorMode();
    const rendersRef = useRef(1);
    
    useEffect(() => {
      // eslint-disable-next-line no-undef
      const localStorageColorMode = localStorage.getItem('theme');
      if (rendersRef.current === 1 && localStorageColorMode) {
        // eslint-disable-next-line no-undef, @typescript-eslint/no-unsafe-member-access
        document.querySelector('.invert').style.filter = localStorageColorMode === 'dark' ? 'invert(1)' : 'none';
      }
      rendersRef.current += 1;
    }, [colorMode]);
  7. slorber commented on Jan 2, 2024

    @slorber
    Collaborator

    @finom this looks like a bad solution leading to FOUC. You don't want to wait for React hydration to invert the image, you want it to be displayed inverted as soon as possible, even if JS is fully disabled.

    Try our ThemedImage component instead: https://docusaurus.io/docs/markdown-features/assets#themed-images

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugclosed: duplicate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions