1

I faced a strange issue when I randomly try to set true or false in useState using Math.random().

Example:

const [hasPrime] = useState(Math.random() < 0.5)

  ...

{hasPrime && (
    <div>
      <p>Free Next-day delivery</p>
    </div>
 )}

Error: Hydration failed because the initial UI does not match what was rendered on the server.

If I put in useState true or false, I will not get such error.

vighnesh153
  • 4,354
  • 2
  • 13
  • 27
JohnPix
  • 1,595
  • 21
  • 44
  • 1
    Does this answer your question? [React 18: Hydration failed because the initial UI does not match what was rendered on the server](https://stackoverflow.com/questions/71706064/react-18-hydration-failed-because-the-initial-ui-does-not-match-what-was-render) – vighnesh153 Feb 04 '23 at 01:51
  • My guess is that next wants a render to be deterministic. In other words, if you render the same thing twice it should have the same result. – Evert Feb 04 '23 at 01:52
  • @vighnesh153 no, it doesn't, my question is more about useState() – JohnPix Feb 04 '23 at 04:17
  • @Evert I am not sure, I found of use Math.random() in example on YouTube for NextJS 12 version. – JohnPix Feb 04 '23 at 04:24

1 Answers1

0

If your server rendered HTML doesn't match the client rendered HTML, the React tree goes out of sync with the DOM. In NextJS, the component is rendered both on the client and on the server. While rendering on your server, Math.random() < 0.5 would have been different from the value generated while rendering on the client which causes the conditional div to be added/removed from the HTML. hence throwing the error. Check out React Hydration Error

When you use true or false in the useState, React will or will not render the conditional div but whatever it renders, it will be the same on both the client side and on the server side.

vighnesh153
  • 4,354
  • 2
  • 13
  • 27