TylerBarnes / gatsby-plugin-transition-link

A link component for page transitions in gatsby
537 stars 71 forks source link

AniLink issue - transition is causing a component to be called multiple times #263

Open PatrickWitmer opened 3 years ago

PatrickWitmer commented 3 years ago

Hello all I'm hoping for a little direction.

Not sure if an issue but would love some ideas or help.

I'm trying to use gatsby-plugin-transition-link, specifically the AniLink part of it. I've set up the transitions and they seem to work fine except for one issue.

I have built a separate component that uses math.floor and math.random to select an image from an array and display a random image from the array on each page load.

The problem is now that I have the transitions it fires the component several times (10ish) resulting in a flickering of random images until it settles on one. Any ideas?

hawkstein commented 3 years ago

I've a few ideas but a link to a repo or example code would help lots here.

PatrickWitmer commented 3 years ago

Thanks @hawkstein I sent you an invite to the repo, sorry I forgot to link it originally.

hawkstein commented 3 years ago

Hi Patrick, the problem you're facing is that the component is indeed rendered multiple times for a couple of reasons but re-rendering is always going to occur with the mdx/transition setup you have I suspect and in general in React anyway ofc. Gonna spell it out in case someone else ever finds this Issue and needs some pointers.

The cause of your problem is the random number function that gets called on every render and changes the image.

`function Randomiser() { const randomAd = millsAds[Math.floor(Math.random() * millsAds.length)]; return ( <>

</> ) }`

The simplest way to fix this in a function component is to add a bit of state with the useState hook:

const [randomAd] = React.useState( millsAds[Math.floor(Math.random() * millsAds.length)] );

An unrelated note: check out gatsby-plugin-image, this would let you have diff versions of the images for mobile/desktop

Hth.

PatrickWitmer commented 3 years ago

Thank you so so much HawkStein. This seemed to fix the flickering. Let me know if I can buy you a coffee or beer or whatever sometime for your help.

richardfreyes commented 2 years ago

How to fix this issue?