Jump to content
GreenSock

GSAP X React


| Cassie
93044

GSAP is a framework-agnostic animation library, that means that you can write the same GSAP code in React, Vue, Angular or whichever framework you chose, the core principles won't change.

That being said - there are some React-specific tips and techniques that will make your life easier!

Need some extra help? Hit up the Reactiflux community for expert advice.

Proper animation cleanup is crucial to avoid unexpected behaviour with React 18's strict mode. This pattern follows React's best practices.

gsap.context makes cleanup nice and simple, all GSAP animations and ScrollTriggers created within the function get collected up so that you can easily revert() ALL of them at once.

Here's the structure:

const comp = useRef(); // create a ref for the root level element (for scoping)
const circle = useRef();

useLayoutEffect(() => {
  
  // create our context. This function is invoked immediately and all GSAP animations and ScrollTriggers created during the execution of this function get recorded so we can revert() them later (cleanup)
  let ctx = gsap.context(() => {
    
    // Our animations can use selector text like ".box" 
    // this will only select '.box' elements that are children of the component
    gsap.to(".box", {...});
    // or we can use refs
    gsap.to(circle.current, { rotation: 360 });
    
  }, comp); // <- IMPORTANT! Scopes selector text
  
  return () => ctx.revert(); // cleanup
  
}, []); // <- empty dependency Array so it doesn't re-run on every render
  
// ...


In this example, React will first render the box and circle elements to the DOM, then GSAP will rotate them 360deg. When this component un-mounts, the animations are cleaned up using ctx.revert().

 

These articles take a deep dive into some best practises and techniques for using GSAP in a React codebase.

gsap-react-colorflare.gif.9761663d78a4b6

Getting Started with GSAP + React

gsap-react-advanced-colorflare.gif.gif.9

Advanced animation techniques

  • Like 3

Get an all-access pass to premium plugins, offers, and more!

Join the Club

We love seeing what you build with GSAP. Don't forget to let us know when you launch something cool.

- Team GreenSock



User Feedback

Recommended Comments



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

×