JS Frameworks
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.
Animation Cleanup
Animation cleanup is important in every framework, but crucial to avoid unexpected behaviour with React 18's strict mode. The following pattern is in line with React's best practices.
Whichever framework you use - it's always a good idea to clean up your animations by removing them when they're no longer needed. This way, you can make sure your animations play nicely and don't cause any hiccups like memory leaks or unexpected glitches.
Cleanup is of particular importance in Single Page Applications (SPAs) and in React codebases as they often involve dynamic content updates and renders - writing your animation code correctly will ensure your animations work reliably within your components lifecycle.
We'll use Vue in these examples as the lifecycle events are nice and clear.
A simple example - revert()
You can call revert on tweens and timeline's directly to kill the animation and return the targets to their pre-animation state. This includes removing any inline styles added by the animation.
let tween;
// create your animation when the component mounts
onMounted(() => {
tween = gsap.to(el,{rotation: 360, repeat: -1})
});
onUnmounted(() => {
tween.revert(); // <- revert your animation when it unmounts
});
So far so good! However, this can get fiddly if you have a lot of animations.
The most efficent way - gsap.context()
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:
let ctx;
onMounted(() => {
// pop all your animatons inside a context
ctx = gsap.context(() => {
gsap.to(el,{rotation: 360, repeat: -1})
let tl = gsap.timeline()
tl.to(box,{x: 200})
tl.to(box,{y: 500, duration: 2})
tl.to(box,{rotation: 180, repeat: 2})
});
onUnmounted(() => {
ctx.revert(); // <- Easy Cleanup!
});
// ...
You can use this pattern in any framework to make cleanup easier.
Take it for a spin - if you get stuck, pop over to the forums and we'll give you a hand.
Starter Templates
Looking for a jump start? Give one of these templates a go.
React
view React demosNext
view Next demosVue
view Vue demosNuxt 3
view Nuxt 3 demos