skip to Main Content

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


  1. 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
    Login or Signup to reply.
  2. I think your useState hook doesn’t write properly, const [loadingText] = useState(getRandomLoadingText) it should const [loadingText, setLoadingText] = useState()

    also, try to use useEffect and use setLoadingText while fetching data

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search