I have a website where I wan't to apply a different background color to some components throughout my website. The site is statically generated using Next.js, and uses Tailwind for styling.
Using the naive approach by selecting a color using Math.random()
won't work, since we can get different results on on the client and the server, and we might see the color quickly changes on first render.
const backgroundColors = ["beige", "purple", "orange"];
const shuffledBackgroundColors = backgroundColors.sort(
() => Math.random() - 0.5
);
Will give us error:
Warning: Prop
className
did not match. Server: "bg-purple" Client: "bg-orange"
My next idea was then to use a pseudo random number generator, so that I could control the seed, and try to make sure we had the same seed on server and client, like this:
import gen from "rand-seed";
const r = new gen(new Date().getUTCMinutes().toString());
const backgroundColors = ["beige", "purple", "orange"];
const shuffledBackgroundColors = backgroundColors.sort(() => r.next() - 0.5);
There might be an edge case were the clock was 30m 59s on the server, and then 31m 0s on the client, but I was willing to live with this. On localhost this seemed to work great, but when I deployed it to Vercel, it looks like there was enough difference between the server and my browser, so it produced bad results.
Ideally it would also select a new random color on each page load, and not just every minute.
Any way to achieve this in a reliable way?