Jump to content
Search Community

using GSAP with Zustand (React state management)

theodieu test
Moderator Tag

Go to solution Solved by GSAP Helper,

Recommended Posts

Hello,

I'm not a pro, so forgive my vocabulary if it's not accurate...

I am trying to find out how I could use GSAP to animate the value of a state managed by Zustand (React state management).

Here is how basic Zustand works:

 

Creating the store:

const useStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

 

Binding components:

function BearCounter() {
  const bears = useStore((state) => state.bears)
  return <h1>{bears} around here...</h1>
}

function Controls() {
  const increasePopulation = useStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

 

 

Let say I want to tween the value of the state bears from 0 to 100.

I would like to understand how to do it using 2 different approaches:

  • how would you do it using a method within the store?
  • how would you do it using a function within the component?

Or are those approaches wrong?

Thank you!

 

 

Link to comment
Share on other sites

  • Solution

Without a minimal demo, it's a bit challenging to offer advice here. If you can provide a Stackblitz or something, that'll go a long way to getting you a solid answer. Just something super simple to illustrate the challenge (not your actual project).

 

In general, though, I can say that GSAP can literally animate anything that JavaScript can touch. So if you've got a special way you need to update a value due to your React plumbing, you could just use an onUpdate, sorta like: 

 

const [value, setValue] = useState(0);

const { contextSafe } = useGSAP();

const onClick = contextSafe(() => {
  const proxy = {value: value};
  gsap.to(proxy, {
    value: value + 10,
    ease: "none",
    duration: 1,
    onUpdate: () => setValue(proxy.value) // <-- update the real thing using React plumbing
  });
});

Here are some starter templates you can fork:

 

Please share the StackBlitz link directly to the file in question (where you've put the GSAP code) so we don't need to hunt through all the files. 

 

Once we see an isolated demo, we'll do our best to jump in and help with your GSAP-specific questions. 

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