Explain how to manage a complex carousel animation with GSAP in React, where slides can be added or removed dynamically and animations need to adjust accordingly.

React JS interview question for Advanced practice.

Answer

Managing a dynamic carousel requires synchronizing GSAP with React's state and props. The animation logic should be entirely driven by the props (slides) and internal state (currentIndex). Approach: 1. Control with State/Props: The component should receive the slides as a prop. The currently active slide should be tracked with a useState hook (currentIndex). 2. useLayoutEffect for Animation: The animation logic should live inside a useLayoutEffect. Its dependency array must include the variables that trigger an animation, such as currentIndex and slides. 3. Cleanup with gsap.context(): This is essential. When the slides prop changes or the currentIndex is updated, the effect re-runs. The revert() function from the context should be called first (in the cleanup function) to remove all previous animations and reset elements to their pre-animation state. Then, the new animations can be created based on the updated DOM. javascript import React, { useState, useLayoutEffect, useRef } from 'react'; import { gsap } from 'gsap'; const Carousel = ({ slides }) = { const compRef = useRef(null); const [currentIndex, setCurrentIndex] = useState(0); useLayoutEffect(() = { const ctx = gsap.context(() = { // Example: animate the incoming slide const currentSlide = compRef.current.children[currentIndex]; gsap.fromTo(currentSlide, { xPercent: 100 }, { xPercent: 0, duration: 0.8, ease: 'power3.inOut' }); }, compRef); // This cleanup runs BEFORE the effect runs again, or on unmount return () = ctx.revert(); }, [currentIndex, slides]); // Re-run animation if the index or the slide data changes // ... JSX to map slides and buttons to update currentIndex return <div ref={compRef}{/ ...slides... /}</div; }; This pattern ensures that every time the data changes, the old animations are completely torn down before new ones are built, preventing conflicts and ensuring the animation always reflects the current state.

Explanation

GSAP's gsap.context() is perfect for this scenario, as it allows you to scope animations to your component and easily clean them all up with ctx.revert() whenever the component needs to re-animate due to new props.

Related Questions