next.js: After client side render following SSR, the rendered html is out of sync with the react tree.

Bug report

Describe the bug

We request the page, and initially it looks fine. It appears server side hydration is working as expected. But a second or so later, after React initialises on the client, some html ends up rendered in the wrong place (sometimes randomly inside sibling elements).

The page source html is correct, so it must be rendering okay on the server. The react tree itself, and where it says the html is, is in line with what we would expect. However the html itself is wrong, and out of sync with the react tree shown in the dev tools. Forcing a re-render in the dev tools appears to fix it.

eg

React tree and page source show:

<div class="a"></div> 
<div class="b"></div> 
<div class="c"></div> 

but actual rendered html is something like:

<div class="a">
  <div class="b"></div> 
</div> 
<div class="c"></div> 

To Reproduce

  1. Go to https://lounge.gamerjibe.com/lounge/MoxieBoosted/members
  2. Create an account and log in (sorry i know that’s annoying… it only replicates when you’re logged in. I promise this isnt some scam to get sign ups haha. It’s a simple one click if you have discord anyway)
  3. See the cards initially look fine.
  4. After some time (it appears to be exactly when commons.js is fully received… Add some network throttling to see the issue clearer) the cards re-render and the html is broken on some of them.
  5. Check the React tree and inspect the broken card. Notice the html does not match the react tree.
  6. Client side navigate to the ‘Home’ tab or anywhere else in the app, and end up back on that members page, and notice that the error does not occur when the page is loaded purely client side.

Expected behavior

The rendered html should match the react tree in the dev tools exactly.

System information

Appears to replicate across all machines and browsers.

Additional context

We’ve also seen this issue in other places in the app, this is just the most obvious one. A pattern we’ve noticed is that it only happens in elements rendered via an array map (ie the cards).

We’ve done all we can to optimise these lists (memoized selectors, unique element keys etc etc) and I really dont think what we’re trying to do should be too much work for react.

It appears to happen when commons.js is loaded. Im not 100% what comes in that file, but i imagine it’s the core react scripts that then initialise and create the virtual DOM, which is why the page rerenders after it loads?

We’re using styled-components, but this issue was present before switching to styled components from sass. You’ll be able to see our redux actions in redux devtools.

I saw on another issue something similar was happening due to invalid html. I’ve run this (https://validator.w3.org/nu/?showsource=yes&doc=https%3A%2F%2Flounge.gamerjibe.com%2Flounge%2FMoxieBoosted%2Fmembers) and fixed the errors locally, but it doesn’t fix the issue.

Any help here would be hugely appreciated. I can’t seem to find anyone else having the same issue.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 16
  • Comments: 29 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Please don’t close this issue, as we’re still not sure where the issue lies. It took me hours to find this discussion!

Has anyone got an update on this?

Basically, what you need to do is do whatever transformations that depend on any browser API just after the component has mounted:

import React from "react";

export default function useHasMounted() {
  const [hasMounted, setHasMounted] = React.useState(false);

  React.useEffect(() => {
    setHasMounted(true);
  }, []);

  return hasMounted;
}
import { useEffect, useState } from "react";
import useHasMounted from "./useHasMounted";

export default function useResponsive() {
  const intialValue = process.browser ? window.innerWidth < 769 : false;
  const [isMobile, setIsMobile] = useState(intialValue);
  const hasMounted = useHasMounted();

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth > 768) {
        setIsMobile(false);
        return;
      }

      setIsMobile(true);
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return isMobile && hasMounted;
}

When React do the rehydration phase, if the output rendered in the server side is different from the generated in the rehydration phase this makes React be confused and makes him render the output in a wrong way, so what you need to do is assure that the output generated by the server be exactly the same to the generated by the rehydration phase (that have access to browser apis, this is the reason why the output differs) and wait for the component to mount, that happens after the rehydration phase to make any changes based in-browser API or any other type of client-side data

This totally makes sense in regards to the warning, but it still seems odd that the end result is just completely mis-rendered html. If it needed to throw away all the SSR’ed elements during hydration (due to the mismatch) why doesn’t the re-render then provide the expected result?

Regardless, using useEffect with some state that keeps track of if the component is mounted solves our issue, much appreciated!

For anyone else who’s curious, you can easily create a wrapper component to skip SSRing some content with something like the following:

import React, {Fragment, useEffect, useState} from 'react'

export const NoSSR = ({children, fallback = null}: NoSSRProps) => {
  const [isMounted, setIsMounted] = useState(false)

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

  return <Fragment>{isMounted ? children : fallback}</Fragment>
}

Hi i had same problem. i solved it eventually. my guess was some kind of SSR conflicts in JSX rendering. so the problem was for the same level elements in the DOM tree. after hours of debugging and adding ID and different name to elements to make them different somehow, i just solve the problem with changing the element name.

so this problem:

<div className="a"></div> 
<div className="b"></div> 
<div className="c"></div> 

can be solve by this:

<div className="a"></div> 
<section className="b"></section> 
<div className="c"></div> 

just be careful about styling and default style of alternative element. for example it is bad idea to replace “div” with “p” or “span” unless you add display block or width 100% to it.

it’s not a fundamental solution but it worked for me. and it was admin panel side in my case so the structure for html was not a concern.

https://github.com/timdavish/next-html-out-of-sync-repro/blob/master/pages/index.js#L6

This is not a bug in your case. SSR + Hydration have to match, otherwise React does a full re-render throwing away the SSR’ed elements, hence why it warns.

Rendering based on if (!process.browser) inside of render/functional components should be avoided, instead you can use useEffect or componentDidMount to know if the app was hydrated/ready.

Here is a repro of what we’re running into: https://github.com/timdavish/next-html-out-of-sync-repro

so @Timer, if people have been able to fix by downgrading, can we accept that this COULD be a bug and reopen the issue?

That useEffect was the key. I had some guard logic to check if I was on the server or not, I removed that and just had a useEffect set the width so I know it will run on the client nad not explode on the server.

For anyone else who’s curious, you can easily create a wrapper component to skip SSRing some content with something like the following

This solution worked for me. Using next version 9.0.6

Thanks @timdavish

but it still seems odd that the end result is just completely mis-rendered html

Please file this bug with the React team if you wish to see the behavior changed.

It’s not a big list issue for us, it’s mixing buttons next to each other; not even in an array, just in a fragment <></>.

Looks like the conflict between SSR and client side rendering can happen pretty much anywhere.

Intersting, I’m glad we aren’t the only ones! We actually upgraded from v7 to v8 in attempt to fix the issue, so for us it was definitely present on older versions too.