I am facing an issue with a component in Next.js (v14.2.1) where I need to display a random string while fetching data. Despite my attempts, I can't seem to maintain the same string on both server and client sides.
Below is the code snippet I am currently using:
const RandomLoadingText = () => {
const possibleLoadingTexts = [
"Asking Chat-GPT for a quote...",
"Not loading...",
"Tickling the Servers for Answers...",
"Convincing the Hamsters to Run Faster...",
"Summoning digital elves to fetch a witty quote...",
];
const getRandomLoadingText = () => {
const randomIndex = Math.floor(Math.random() * possibleLoadingTexts.length);
return possibleLoadingTexts[randomIndex] as never;
};
const [loadingText] = useState(getRandomLoadingText)
return (
<div>
<span className={`${lobster.className} text-lg`}>"</span>
{loadingText}
<span className={`${lobster.className} text-lg`}>"</span>
</div>
);
};
export default RandomLoadingText;
Despite attempting to choose a random string from an array for display during data fetching, I'm encountering issues where the string differs between Server-Side Rendering (SSR) and Client-Side Rendering (CSR), resulting in hydration errors.