Capítulo 9 de 411

Chapter 9: gsap.context()

Core Idea

gsap.context() collects every GSAP animation and ScrollTrigger created inside a function so they can all be reverted or killed together, and optionally scopes selector text to one root element.

Key Concepts

  • Collection: wraps a function; any gsap.to/from/timeline/... calls made inside it get tracked automatically.
  • ctx.revert(): instantly undoes and removes everything the context collected, restoring original inline styles.
  • Scoping: pass a second argument (element or ref) to scope internal selector text (gsap.to(".box", ...)) to descendants of that root — useful in React/Angular to avoid manual refs.
  • React: the useGSAP() hook wraps this pattern with automatic cleanup, and is the recommended approach in React instead of calling gsap.context() directly.

Code Examples

let ctx = gsap.context(() => {
  gsap.to(".box", { x: 100 });
  gsap.timeline().to(".a", { opacity: 0 }).to(".b", { opacity: 0 });
});

// later, undo everything created above in one call:
ctx.revert();
  • What it demonstrates: cleaning up an arbitrary number of animations without manually tracking each one in a variable.

Key Takeaways

  1. Added in GSAP 3.11 specifically to solve cleanup in component-based frameworks (React, Vue, Angular).
  2. Prefer the useGSAP() React hook over calling gsap.context() by hand in React code.

Connects To

  • useGSAP() (React): framework-specific wrapper around this same pattern.