I have this component in Next.js (v14.2.1) which, essentially, all it does is to pick a random string while i fetch some data. However, i’ve been trying to persist the same string on server and client side without any luck.
I honestly don’t know what else to do.
Here’s my current code:
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;
I simply tried picking a random string in an array to display while i fetch some data, but the string changes between SSR and CSR causing Hydration errors.
2
Answers
I can think of 2 options to solve this:
I think your useState hook doesn’t write properly,
const [loadingText] = useState(getRandomLoadingText)
it shouldconst [loadingText, setLoadingText] = useState()
also, try to use useEffect and use setLoadingText while fetching data