Describe how to handle a GSAP animation that needs to react to a user interaction, like a hover event, while preventing conflicts if the user hovers in and out rapidly.
React JS interview question for Advanced practice.
Answer
To handle hover animations and prevent conflicts from rapid interactions, you should create two separate functions for the enter and leave animations. The key is to immediately kill any active animations on the target element before starting a new one. This ensures that if the user hovers out while the 'in' animation is still running, it stops instantly and the 'out' animation begins from the current visual state. jsx import React, { useRef } from 'react'; import gsap from 'gsap'; function HoverComponent() { const boxRef = useRef(null); const handleMouseEnter = () = { // Kill any existing animations on the element first gsap.killTweensOf(boxRef.current); // Start the 'in' animation gsap.to(boxRef.current, { scale: 1.2, duration: 0.3 }); }; const handleMouseLeave = () = { // Kill any existing animations on the element first gsap.killTweensOf(boxRef.current); // Start the 'out' animation gsap.to(boxRef.current, { scale: 1, duration: 0.3 }); }; return ( <div ref={boxRef} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} style={{ width: 100, height: 100, background: 'purple' }} / ); } In this solution, gsap.killTweensOf(boxRef.current) is called at the beginning of both event handlers. This guarantees that you always start from a clean slate, preventing animations from fighting each other and leading to jerky or unexpected behavior during rapid mouse movements.
Explanation
GSAP automatically handles tween overwriting. By default, if you create a new tween on a property that is already being animated, the new tween will take priority. This can often handle rapid interactions smoothly without manual cleanup.