HelloWorld0274
HelloWorld0274

Reputation: 21

Minified React error #423 and #418 (Math.random)

I'm trying to A/B test some ads on my React / GatsbyJS website. For that I render the ads depending if a random number is bigger or smaller than .5

I'm receiving a Minified React error #423 and Minified React error #418 error, because I'm using const randomNr = Math.random(), which React doesn't like because the output will be different on render than on hydration.

I can't find a simple workaround to fix this issues. I tried using useEffect, useState or useLayoutEffect, but that breaks the script of the ads. Since my method works and doesn't break anything, I could simply ignore it, but I want to remove the error for SEO reasons. Any ideas?

Upvotes: 2

Views: 5988

Answers (1)

GLHF
GLHF

Reputation: 4035

You should be able to solve this via generating the number only on the client side. Don't use server side to do this. You'll also lose benefits of build generation data that Gatsby provides.

useEffect(() => {
    const randomNr = Math.random()

    // your logic
  }, []); // this will trigger ONCE only after the first render of the page

If you have dependency, like you need a new random number everytime a value changes, then

useEffect(() => {
        const randomNr = Math.random()
    
        // your logic
      }, [yourValue]); // this will trigger EVERYTIME when yourValue changes

yourValue is usually a state.

Upvotes: 0

Related Questions