Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js/React warning when generating random values in a component

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?

like image 787
Koen Avatar asked Nov 28 '17 19:11

Koen


2 Answers

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

like image 140
zenoh Avatar answered Oct 15 '22 18:10

zenoh


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>
like image 21
FooBar Avatar answered Oct 15 '22 18:10

FooBar