Jump to content
Search Community

How to trigger setState with gsap?

Rahul Ahire test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

  • Solution

Hi,

 

Nick is right, you should use the rich callbacks system GSAP has to offer:

https://greensock.com/docs/v3/GSAP/Tween

 

Although in this case maybe using onUpdate and the Snap Plugin could be a better fit than onComplete:

https://stackblitz.com/edit/react-ukxyjf?file=src%2FApp.js

 

Let us know if you have more questions.

 

Happy Tweening!

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

Hi,

 

GSAP will call the onUpdate callback on every tick (GSAP's internal clock) which will cause the setCount method to be updated, but React will know when the new value is different from the previous and only then will trigger a re-render. GSAP ticker gets called 60 times per second but with the SnapPlugin working the value won't be different on every update.

 

In this type of situations you should definitely create the smallest possible component so re-renders affect only that component and a small portion of the DOM, something like this:

const MyCount = ({ value, duration, ease }) => {
  const [count, setCount] = useState(0);
  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      const myCountObj = { number: 0 };
      gsap.to(myCountObj, {
        duration,
        ease: ease || "none",
        number: value,
        onUpdate: () => {
          setCount([myCountObj.number]);
        },
      })
    });
    
    return () => ctx.revert();
  }, [value]);
  return (
    <div>{ count }</div>
  );
};

export default MyCount;

Re-rendering that shouldn't create a performance problem.

 

Then in your app just use it like this:

const App = () => {
  return (
    <div>
      <MyCount value={10} duration={5} />
    </div>
  );
};

 

Happy Tweening!

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...