Search code examples
javascriptnext.jsrandomserver-side-rendering

My random string picker is choosing a different string on server side and client side


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.


Solution

  • I can think of 2 options to solve this:

    1. Generate the random index from RSC and pass to the client component via props.
    2. use useEffect and setState only once there once initialized. Initial state maybe empty string