Jump to content
Search Community

React setState during scrollTrigger problem

Niom test
Moderator Tag

Recommended Posts

Hi everyone,

 

I'm pretty new to both react and GSAP animation. I'm basically trying to reproduce this effect here: 

 

The main difference is that instead of changing the innerHTML of an element, I want to update a variable in state, to, for example, change the value of an input fied and in the future a progress bar. 

const [count, setCount] = React.useState(0);

    useLayoutEffect(()=>{
        gsap.registerPlugin(ScrollTrigger)
        const ctx = gsap.context(() => {
            const myObj = { val: 0 };
            
            gsap.to(myObj, {
                val: 1000,
                duration: 5,
                ease:"none",
                    onUpdate: () => {
                        setCount(myObj.val)
                    },
                scrollTrigger: {
                    trigger: '#hallo',
                    start: 'top center',
                    end: '+=500',
                    markers: true,
                    scrub: true
                }
            })
        });
        return () => ctx.revert();

    },[count])

    return(
        <div id={'hallo'}><Input value={count}/></div>
    );

 

I must be doing something wrong, it would be amazing if someone could help me out.

 

Thank you in advance :)

Link to comment
Share on other sites

Welcome to the forums, @Niom

 

Thanks for being a Club GreenSock member. 💚

 

Disclaimer: I'm not a React guy but...

 

I'd bet the issue is that you put [count] as your dependency Array in that useLayoutEffect() which basically means "every time count changes, re-run this useLayoutEffect() after calling its cleanup function". So you're creating a nasty loop that's very expensive performance-wise. Inside your useLayoutEffect(), you're creating an animation that changes the count 60 times per second. Every time it changes, it basically flushes that animation and re-creates a new one all over again, with a ScrollTrigger too (after destroying the old one). So it's constantly creating animations over and over and over again. 

 

Try removing count from the dependency Array. Just use an empty Array. Does that help? 

 

I'd strongly recommend checking this out:

 

If that doesn't help, please provide a minimal demo - here's a React starter template you can fork. We'd be glad to take a peek. 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...