Describe how you would implement responsive animations with GSAP in a React application that adapt to different screen sizes. What modern GSAP features would be most beneficial?

React JS interview question for Advanced practice.

Answer

To create responsive animations with GSAP in React, the modern best practice is to use gsap.matchMedia(). This feature allows you to create different animation timelines for different viewport breakpoints, and it integrates perfectly with React's lifecycle through gsap.context(). Here's an example: javascript import React, { useLayoutEffect, useRef } from 'react'; import { gsap } from 'gsap'; const MyResponsiveComponent = () = { const containerRef = useRef(null); useLayoutEffect(() = { const ctx = gsap.context(() = { gsap.matchMedia() .add('(min-width: 768px)', () = { // Animation for larger screens gsap.to('.myElement', { x: '50vw', duration: 1, ease: 'power2.out' }); }) .add('(max-width: 767px)', () = { // Animation for smaller screens gsap.to('.myElement', { x: '25vw', duration: 0.75, ease: 'sine.inOut' }); }); }, containerRef); return () = ctx.revert(); // Cleanup on unmount }, []); return ( <div ref={containerRef} <div className='myElement'Responsive Element</div </div ); }; This code uses gsap.matchMedia() to define different animations based on screen width. When the viewport size changes (e.g., on window resize), GSAP automatically reverts the old animations and applies the new ones that match the current conditions. The gsap.context() wrapper ensures all these matchMedia instances are properly cleaned up when the component unmounts.

Explanation

GSAP's matchMedia is specifically designed to make responsive animations declarative and easy to manage, and it automatically handles cleanup when conditions no longer match.

Related Questions