16

I'm building a next.js app that generates some random numbers which generates the warning:

Warning: Text content did not match. Server: "1" Client: "2"

I think I understand why I get this warning (the virtual DOM is kinda-sorta-out-of-sync with what was sent from the server). I'm just wondering if there's a way to let next.js/React know that this is ok in this situation. Or is there a way to only generate the random on the server and let the client use this as a literal?

Or should I just ignore the warning?

Koen
  • 3,571
  • 1
  • 32
  • 52

2 Answers2

10

Moving JavaScript random variable into React state solved the problem for me.

Here's my problem (simplified) before:

function RandomNumber() {
  const randomNumber = Math.floor(Math.random() * 100);
  return <p>{randomNumber}</p>;
}

After

function RandomNumber() {
  const [randomNumber, setRandomNumber] = useState(undefined);

  useEffect(() => {
    setRandomNumber(Math.floor(Math.random() * 100));
  }, []);

  return <p>{randomNumber}</p>;
}

My code used React Hooks useState and useEffect, but previous React lifecycle methods setState and componentDidMount should work fine too

zenoh
  • 1,931
  • 1
  • 20
  • 36
1

What I would suggest is that you wrap the content that you have some random generated content in, inside a component.

components/NoSsr.js

import dynamic from 'next/dynamic';
import React from 'react';

const NoSsr = ({ children }) => <>{children}</>;

export default dynamic(() => Promise.resolve(NoSsr), {
  ssr: false,
});

And then in your file:

<NoSsr>
    { Math.random() }
</NoSsr>
FooBar
  • 5,164
  • 10
  • 42
  • 76