Jump to content
Search Community

best way to animate button on hover in react

Sherlok test
Moderator Tag

Go to solution Solved by Cassie,

Recommended Posts


I try to do onMouseEnter and onMouseLeave animation timeline.

The example is located here https://codesandbox.io/s/serene-lena-5o2lhi?file=/src/App.js

I store my timeline in useRef and then onEnter I use currentTarget and then just create the timeline and assign it tlRef. And in onLeave function I just do the reverse.

From the first view, it seems it works fine, but when I try to hover and leave quickly and do it multiple times and the animation gets stuck.

Could you please explain where I am wrong and what is the best practice for that?



Link to comment
Share on other sites

Heya, something like this should work


You don't want to be creating a new timeline every time you hover. timelines are also for sequences of animations, if you have one action happening on hover you can just use a tween.

We have a whole guide here if you'd like to know more about best practises in React


Good luck!


Link to comment
Share on other sites

Thanks for your reply @Cassie

and what if have complex button with icon and I want to move icon on hover and also overlay? Should I use the same principle and don’t create the timeline inside the hover function?


Just modify your example 



Seems it works fine. Actually my main concern is not to rewrite the same animation in onMouseLeave function. So, just wondering is it ok to write in context like this?

Link to comment
Share on other sites

  • Solution

Yep, that's the idea!


One tweak, keep all your animations inside the GSAP context so that they get killed on cleanup. ☺️

useLayoutEffect(() => {
  let ctx = gsap.context(() => {
    gsap.set(overlay.current, { xPercent: -100 });

    tl.current = gsap.timeline({ paused: true })
    .to(".text", { color: "black" })
    .to(".overlay", { xPercent: 0 }, "<");

  return () => ctx.revert();
}, []);


  • Like 1
  • Thanks 1
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...