Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

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

Open
PatrickWitmer opened this issue Mar 10, 2021 · 5 comments

Comments

@PatrickWitmer
Copy link

PatrickWitmer commented Mar 10, 2021

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
Copy link

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

@PatrickWitmer
Copy link
Author

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

@hawkstein
Copy link

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.

@PatrickWitmer
Copy link
Author

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
Copy link

How to fix this issue?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants