gatsby-plugin-transition-link
gatsby-plugin-transition-link copied to clipboard
AniLink issue - transition is causing a component to be called multiple times
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?
I've a few ideas but a link to a repo or example code would help lots here.
Thanks @hawkstein I sent you an invite to the repo, sorry I forgot to link it originally.
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 ( <> <img src={randomAd}/> </> ) }
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.
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.
How to fix this issue?