I am faced with a challenge on my website where I need to implement different background colors for various components throughout the site. The website is generated statically using Next.js and styled using Tailwind.
Simply selecting a color using Math.random()
is not a viable solution, as it may result in different colors between the client and server, causing the color to change rapidly upon initial render.
const backgroundColors = ["beige", "purple", "orange"];
const shuffledBackgroundColors = backgroundColors.sort(
() => Math.random() - 0.5
);
This approach leads to an error:
Warning: Prop
className
did not match. Server: "bg-purple" Client: "bg-orange"
To address this issue, I considered using a pseudo-random number generator where I could control the seed to ensure consistency between the server and client:
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);
While this method seemed effective on localhost, deploying it to Vercel revealed discrepancies between the server and browser, resulting in undesirable outcomes.
Ultimately, the goal is to have a reliable way to select a new random color on each page load, rather than just once per minute.
Is there a more dependable approach to achieve this?