Course contentsShow
← React
Lesson 2002 of 2,39645. AnimationsFree lesson

gsap.to() in useEffect: Single Element Animations

Animating a ref'd element with gsap.to() inside useEffect, managing animation lifecycle and cleanup.

gsap.to() in useEffect: Single Element Animations

You'll learn how to animate a single DOM element using GSAP's gsap.to() method inside useEffect, with proper lifecycle management.

Why useEffect for GSAP Animations

GSAP manipulates the DOM directly, so you need to wait until your component mounts and the element exists. useEffect is the perfect hook for this—it runs after the initial render when your ref'd element is ready.

The Basic Pattern

import { useRef, useEffect } from 'react';
import { gsap } from 'gsap';

function AnimatedBox() {
  const boxRef = useRef(null);

  useEffect(() => {
    // Animate the ref'd element
    gsap.to(boxRef.current, {
      x: 200,
      duration: 1,
      ease: 'power2.out'
    });
  }, []); // Empty array: animate only on mount

  return <div ref={boxRef} className="box" />;
}

The gsap.to() method takes two arguments: the target element and an object describing the end state. GSAP handles the interpolation from the current state to your target values.

Cleanup and Animation Lifecycle

GSAP animations should be killed when components unmount to prevent memory leaks:

useEffect(() => {
  const animation = gsap.to(boxRef.current, {
    rotation: 360,
    duration: 2,
    repeat: -1 // Infinite loop
  });

  // Cleanup function
  return () => {
    animation.kill();
  };
}, []);

Think of animation.kill() like turning off a sprinkler when you leave the yard—you don't want it running when no one's watching.

When to Trigger Animations

An empty dependency array means "animate once on mount." Add dependencies if you want animations to re-trigger when state or props change.

Key Takeaway: Use gsap.to() inside useEffect to animate ref'd elements after mount, and always return a cleanup function that calls animation.kill() to prevent memory leaks when the component unmounts.