Explain the best practices for integrating GSAP into a React application, focusing on lifecycle management and cleanup to prevent memory leaks.

React JS interview question for Advanced practice.

Answer

The modern best practice for integrating GSAP into React revolves around using the gsap.context() utility within a useEffect or useLayoutEffect hook. 1. Use useRef for Element References: Always use useRef to get direct, reliable references to DOM nodes instead of string-based selectors. 2. Use useEffect or useLayoutEffect: Place all GSAP initialization code within one of these hooks to ensure the DOM elements exist before you try to animate them. 3. Use gsap.context() for Scoped Animations and Cleanup: This is the most crucial step. By wrapping your GSAP code in a context, you create a sandboxed environment for your animations. The revert() method on the returned context object will then clean up only the animations created within that scope. javascript import React, { useLayoutEffect, useRef } from 'react'; import gsap from 'gsap'; const MyComponent = () = { const comp = useRef(null); // Ref for the component's root element useLayoutEffect(() = { // Create a context and scope it to the component's root let ctx = gsap.context(() = { gsap.to('.box', { rotation: 360 }); }, comp); // The return function from the effect is the cleanup function return () = ctx.revert(); }, []); return <div ref={comp}<div className="box"Box</div</div; }; In this example, ctx.revert() is called when the component unmounts. It finds all GSAP animations and ScrollTriggers created inside the context function and safely removes them, preventing memory leaks and side effects.

Explanation

The gsap.context() feature was introduced in GSAP 3.11 to make framework-specific cleanup significantly easier and more reliable.

Related Questions