Orchestrating GSAP Context and Lenis in Vue 3 for Smooth Transitions Without Memory Leaks
A technical analysis on how to integrate Lenis smooth scrolling with the Vue 3 lifecycle and GSAP ScrollTrigger, preventing memory leaks and DOM desynchronization when navigating.
When I tackled the layout and frontend development of La Rúcula Gastrobar, the goal was clear from day one: the visual experience and scroll fluidity had to match the culinary identity of the place. La Rúcula is an editorial menu-focused website for a restaurant in Chiclana, where images, starter descriptions, and section transitions carry fundamental aesthetic weight. To achieve that seamless motion, I used a stack consisting of Vue 3, Vite, Tailwind CSS, GSAP with ScrollTrigger, and Lenis for smooth scrolling.
However, bringing complex scroll-driven animations into a Single Page Application (SPA) introduces architectural lifecycle issues that don't exist in a traditional static website. If component unmounting, scroll triggers, and the interpolation engine aren't managed with precision, the application starts accumulating memory leaks, layout shifts, and null DOM references as users navigate between routes.
The Lifecycle Problem in Animated Applications
In a Vue 3 application built with Vue Router, views and components mount and unmount dynamically based on user interaction. When creating animations with GSAP tied to the scroll position via the ScrollTrigger plugin, the library calculates initial and final coordinates for HTML elements and injects global event listeners into the browser window.
If the user moves from the menu view to another section without explicitly clearing those triggers, a serious issue arises: ScrollTrigger listeners remain active in memory, referencing DOM nodes that Vue has already removed from the virtual tree. This triggers several cascading failures:
- Memory leaks accumulate, progressively degrading client performance after visiting several pages.
- ScrollTrigger attempts to recalculate positions on elements whose height and screen position have dropped to zero.
- The animation engine throws warnings and errors in the console when trying to manipulate properties of non-existent elements.
Added to this is the presence of Lenis. Lenis replaces native scroll behavior with an inertial mathematical interpolation driven by its own render loop (requestAnimationFrame). If Vue Router changes the active route while Lenis maintains residual scroll velocity, the new page begins at an arbitrary scroll position, misaligning any spatial calculations performed by GSAP when mounting the new component.
GSAP Context as a Containment Mechanism in the Composition API
To resolve the unintended persistence of animations across the Vue 3 lifecycle, the structural solution is to wrap all creation of timelines and ScrollTriggers inside the gsap.context() API. This function acts as a scoped container that automatically tracks any animation, instance, or trigger generated within it.
The core advantage of gsap.context() within the Composition API is its seamless integration with the onUnmounted hook. When the view component is destroyed, the context's .revert() method is invoked. This not only stops active timelines, but also completely removes associated ScrollTriggers and cleans up any inline CSS styles that GSAP applied directly to the DOM.
In the menu of La Rúcula Gastrobar, I implemented this pattern in key sections to ensure a clean lifecycle:
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import gsap from 'gsap'
import ScrollTrigger from 'gsap/ScrollTrigger'
gsap.registerPlugin(ScrollTrigger)
const menuContainer = ref(null)
let ctx
onMounted(() => {
ctx = gsap.context((self) => {
const items = self.selector('.menu-item')
items.forEach((item) => {
gsap.from(item, {
y: 40,
opacity: 0,
duration: 0.8,
ease: 'power2.out',
scrollTrigger: {
trigger: item,
start: 'top 85%',
toggleActions: 'play none none reverse'
}
})
})
}, menuContainer.value)
})
onUnmounted(() => {
if (ctx) {
ctx.revert()
}
})
</script>
<template>
<main ref="menuContainer" class="menu-wrapper min-h-screen bg-neutral-900 text-neutral-100 p-8">
<section class="max-w-4xl mx-auto space-y-12">
<article class="menu-item border-b border-neutral-800 pb-6">
<h2 class="text-2xl font-serif">Starters</h2>
<p class="text-neutral-400 mt-2">Fresh seasonal selection with local ingredients.</p>
</article>
<article class="menu-item border-b border-neutral-800 pb-6">
<h2 class="text-2xl font-serif">Fish & Seafood</h2>
<p class="text-neutral-400 mt-2">Catch of the day grilled with olive oil.</p>
</article>
</section>
</main>
</template>Passing menuContainer.value as the second argument to gsap.context() is crucial. This scopes the .menu-item CSS selector exclusively to the component's root node. If other elements share the same class name in the footer or sibling components, GSAP ignores them without interfering.
Synchronizing Lenis and ScrollTrigger Without Frame Drops
Once component-level cleanup is guaranteed, the next technical challenge is synchronizing Lenis's render loop with GSAP's internal clock. By default, GSAP updates its animations via its own ticker. If Lenis runs its scroll loop independently, both engines end up competing to update the DOM at slightly offset moments during browser rendering, causing visible micro-stuttering.
To tightly coordinate them, I configured a global Lenis instance whose render step is driven directly by GSAP's ticker, while connecting Lenis's scroll event to ScrollTrigger position updates:
import { onMounted, onUnmounted } from 'vue'
import Lenis from 'lenis'
import gsap from 'gsap'
import ScrollTrigger from 'gsap/ScrollTrigger'
export function useSmoothScroll() {
let lenis: Lenis | null = null
onMounted(() => {
lenis = new Lenis({
duration: 1.2,
easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
smoothWheel: true
})
lenis.on('scroll', ScrollTrigger.update)
const updateFn = (time: number) => {
lenis?.raf(time * 1000)
}
gsap.ticker.add(updateFn)
gsap.ticker.lagSmoothing(0)
})
onUnmounted(() => {
if (lenis) {
lenis.destroy()
gsap.ticker.remove(lenis.raf)
}
})
return {
lenis
}
}The gsap.ticker.lagSmoothing(0) call plays a fundamental role. By default, GSAP includes a lag smoothing mechanism that slows down animations if it detects a drop in frames per second to preserve temporal consistency. In animations tied to physical mouse wheel movement via Lenis, this automatic adjustment conflicts directly with inertial acceleration. Disabling lagSmoothing eliminates this added latency and aligns the calculation frequency.
Managing Coordinates in Vue Router Transitions
The final piece of this architecture comes into play when navigating between views. When users click a different route while scrolled to the bottom of the page, Vue Router updates the component tree without immediately resetting the physical scroll position unless explicitly instructed to do so.
If the incoming view calculates its start and end positions using ScrollTrigger before the scroll resets to the top (top: 0), animations trigger prematurely or compute offset values skewed by the height of the outgoing page.
In the Vue Router setup, I solved this by combining the library's native scroll behavior with a deferred ScrollTrigger engine refresh using nextTick:
import { createRouter, createWebHistory } from 'vue-router'
import { nextTick } from 'vue'
import gsap from 'gsap'
import ScrollTrigger from 'gsap/ScrollTrigger'
const router = createRouter({
history: createWebHistory(),
routes: [
// Project route definitions
],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { top: 0 }
}
}
})
router.afterEach(async () => {
await nextTick()
ScrollTrigger.refresh()
})
export default routerBy calling ScrollTrigger.refresh() right after Vue finishes processing node tree changes in the nextTick() cycle, we ensure that the DOM of the new route already has its actual layout dimensions assigned before scroll trigger zones are calculated.
Optimizing Paint Operations with GPU-Accelerated Properties
Pairing lifecycle management with efficient Tailwind CSS code is vital to prevent repaint bottlenecks during smooth scrolling execution. Animating properties like margin, top, or height forces the browser engine to recalculate global page geometry on every frame.
At La Rúcula Gastrobar, I restricted scroll animations exclusively to two properties manipulated by GSAP: transform (via y or x translations) and opacity. These properties are processed directly on the Graphics Processing Unit (GPU) without triggering layout reflows.
Using Tailwind CSS, I applied layer-hinting classes like will-change-transform or transform-gpu exclusively to cards or containers with complex animation sequences. This instructs the browser to promote those elements to a dedicated compositor layer on the GPU before the animation starts, preventing sudden render performance drops during fast scrolling.
Closing Thoughts and Final Considerations
Designing a visually impactful web interface requires balancing visual ambition with core software engineering principles. Animation and smooth scroll libraries offer massive creative possibilities, but using them within a reactive ecosystem like Vue 3 requires strict control over the lifecycle of every object placed in memory.
By leveraging gsap.context() to encapsulate event cleanup, explicitly integrating Lenis into GSAP's ticker, and resynchronizing layout dimensions after every route change with Vue Router, I ensured that La Rúcula Gastrobar performs as a robust, fluid, and predictable application. Making sure every mounted resource is torn down without a trace is key to building memorable interactive experiences without compromising system stability.