Skip to main content

Advanced techniques

Before we begin

Are you working with React and looking to really advance your GSAP animation skills? You're in the right place. This guide contains advanced techniques and some handy tips from expert animators in our community.

This is not a tutorial, so feel free to dip in and out as you learn. Think of it as a collection of recommended techniques and best practices to use in your projects.

If you're starting out we highly recommend reading our foundational article first.

Why choose GSAP?

There are React-specific libraries that offer a simpler more declarative approach. So why choose GSAP?

Animating imperatively gives you a lot more power, control and flexibility. Your imagination is the limit. You can reach for GSAP to animate everything from simple DOM transitions to SVG, three.js, canvas or WebGL.

More importantly, you can rely on us. We obsess about performance, optimizations and browser compatibility so that you can focus on the fun stuff. We've actively maintained and refined our tools for over a decade and listen to the needs of the community.

Lastly, if you ever get stuck, our friendly forum community is there to help. 💚

Going forward we will assume a comfortable understanding of both GSAP and React.

Online playgrounds

Get started quickly by forking one of these starter templates:

Component Communication

In the last article, we covered creating our first animation, and how to create and control timelines within a React component. But there are times where you may need to share a timeline across multiple components or construct animations from elements that exist in different components.

In order to achieve this, we need a way to communicate between our components.

There are 2 basic approaches to this.

  1. a parent component can send down props, e.g. a timeline
  2. a parent component can pass down a callback for the child to call, which could add animations to a timeline.

Passing down a timeline prop

Note that we are using useState instead of useRef with the timeline. This is to ensure the timeline will be available when the child renders for the first time.

function Box({ children, timeline, index }) {
const el = useRef();
// add 'left 100px' animation to timeline
useLayoutEffect(() => {
timeline && timeline.to(el.current, { x: -100 }, index * 0.1);
}, [timeline]);

return <div className="box" ref={el}>{children}</div>;
}

function Circle({ children, timeline, index, rotation }) {
const el = useRef();

useLayoutEffect(() => {
// add 'right 100px, rotate 360deg' animation to timeline
timeline && timeline.to(el.current, { rotate: rotation, x: 100 }, index * 0.1);
}, [timeline, rotation]);

return <div className="circle" ref={el}>{children}</div>;
}

function App() {
const [tl, setTl] = useState();

return (
<div className="app">
<button onClick={() => setReversed(!reversed)}>Toggle</button>
<Box timeline={tl} index={0}>Box</Box>
<Circle timeline={tl} rotation={360} index={1}>Circle</Circle>
</div>
);
}

loading...

Passing down a callback to build a timeline

function Box({ children, addAnimation, index }) {
const el = useRef();

useLayoutEffect(() => {
const animation = gsap.to(el.current, { x: -100 });
addAnimation(animation, index);

return () => animation.progress(0).kill();
}, [addAnimation, index]);

return <div className="box" ref={el}>{children}</div>;
}

function Circle({ children, addAnimation, index, rotation }) {
const el = useRef();

useLayoutEffect(() => {
const animation = gsap.to(el.current, { rotate: rotation, x: 100 });
addAnimation(animation, index);

return () => animation.progress(0).kill();
}, [addAnimation, index, rotation]);

return <div className="circle" ref={el}>{children}</div>;
}


function App() {
// define a timeline
const [tl, setTl] = useState();
// pass a callback to child elements, this will add animations to the timeline
const addAnimation = useCallback((animation, index) => {
tl.add(animation, index * 0.1);
}, [tl]);

return (
<div className="app">
<button onClick={() => setReversed(!reversed)}>Toggle</button>
<Box addAnimation={addAnimation} index={0}>Box</Box>
<Circle addAnimation={addAnimation} index={1} rotation="360">Circle</Circle>
</div>
);
}

loading...

React Context

Passing down props or callbacks might not be ideal for every situation.

The component you're trying to communicate with may be deeply nested inside other components, or in a completely different tree. For situations like this, you can use React's Context.

Whatever value your Context Provider provides will be available to any child component that uses the useContext hook.

const SelectedContext = createContext();

function Box({ children, id }) {
const el = useRef();
const { selected } = useContext(SelectedContext);
const ctx = gsap.context(() => {});

useLayoutEffect(() => {
return () => ctx.revert();
}, []);

useLayoutEffect(() => {
ctx.add(() => {
gsap.to(el.current, {
x: selected === id ? 200 : 0
});
});
}, [selected, id]);

return <div className="box" ref={el}>{children}</div>;
}

function Boxes() {
return (
<div className="boxes">
<Box id="1">Box 1</Box>
<Box id="2">Box 2</Box>
<Box id="3">Box 3</Box>
</div>
);
}

function Menu() {

const { selected, setSelected } = useContext(SelectedContext);

const onChange = (e) => {
setSelected(e.target.value);
};

return (
<div className="menu">
<label>
<input
onChange={onChange}
checked={selected === "1"}
type="radio"
value="1"
name="selcted"/> Box 1
</label>
<label>
<input
onChange={onChange}
checked={selected === "2"}
type="radio"
value="2"
name="selcted"/> Box 2
</label>
<label>
<input
onChange={onChange}
checked={selected === "3"}
type="radio"
value="3"
name="selcted"/> Box 3
</label>
</div>
);
}

function App() {
const [selected, setSelected] = useState("2");

return (
<div className="app">
<SelectedContext.Provider value={{ selected, setSelected }}>
<Menu />
<Boxes />
</SelectedContext.Provider>
</div>
);
}

loading...

Imperative Communication

Passing around props or using Context works well in most situations, but using those mechanisms cause re-renders, which could hurt performance if you're constantly changing a value, like something based on the mouse position.

To bypass React's rendering phase, we can use the useImperativeHandle hook, and create an API for our component.

const Circle = forwardRef((props, ref) => {
const el = useRef();

useImperativeHandle(ref, () => {

// return our API
return {
moveTo(x, y) {
gsap.to(el.current, { x, y });
}
};
}, []);

return <div className="circle" ref={el}></div>;
});

Whatever value the imperative hook returns will be forwarded as a ref

function App() {    
const circleRef = useRef();

useLayoutEffect(() => {
// doesn't trigger a render!
circleRef.current.moveTo(300, 100);
}, []);

return (
<div className="app">
<Circle ref={circleRef} />
</div>
);
}

loading...

Creating reusable animations

Creating reusable animations is a great way to keep your code clean while reducing your app's file size. The simplest way to do this would be to call a function to create an animation.

function fadeIn(target, vars) {
return gsap.from(target, { opacity: 0, ...vars });
}

function App() {
const box = useRef();

useLayoutEffect(() => {
const animation = fadeIn(box.current, { x: 100 });
}, []);

return <div className="box" ref={box}>Hello</div>;
}

For a more declarative approach, you can create a component to handle the animation.

function FadeIn({ children, vars }) {
const el = useRef();

useLayoutEffect(() => {
const ctx = gsap.context(() => {
animation.current = gsap.from(el.current.children, {
opacity: 0,
...vars
});
});
return () => ctx.revert();
}, []);

return <span ref={el}>{children}</span>;
}

function App() {
return (
<FadeIn vars={{ x: 100 }}>
<div className="box">Box</div>
</FadeIn>
);
}

loading...

If you want to use a React Fragment or animate a function component, you should pass in a ref for the target(s).

RegisterEffect()

GSAP provides a way to create reusable animations with registerEffect()

function GsapEffect({ children, targetRef, effect, vars }) {  

useLayoutEffect(() => {
if (gsap.effects[effect]) {
ctx.add(() => {
animation.current = gsap.effects[effect](targetRef.current, vars);
});
}
}, [effect]);

return <>{children}</>;
}

function App() {
const box = useRef();

return (
<GsapEffect targetRef={box} effect="spin">
<Box ref={box}>Hello</Box>
</GsapEffect>
);
}

loading...

Exit animations

To animate elements that are exiting the DOM, we need to delay when React removes the element. We can do this by changing the component's state after the animation has completed.

function App() {      
const boxRef = useRef();
const [active, setActive] = useState(true);
const [ctx, setCtx] = useState(gsap.context(() => {}, app));

useLayoutEffect(() => {
ctx.add("remove", () => {
gsap.to(ctx.selector(".box"), {
opacity: 0,
onComplete: () => setActive(false)
});
});
return () => ctx.revert();
}, []);

return (
<div>
<button onClick={ctx.remove}>Remove</button>
{ active ? <div ref={boxRef}>Box</div> : null }
</div>
);
}

loading...

The same approach can be used when rendering elements from an array.

function App() {    

const [items, setItems] = useState([
{ id: 0 },
{ id: 1 },
{ id: 2 }
]);

const removeItem = (value) => {
setItems(prev => prev.filter(item => item !== value));
}

useLayoutEffect(() => {
ctx.add("remove", (item, target) => {
gsap.to(target, {
opacity: 0,
onComplete: () => removeItem(item)
});
});
return () => ctx.revert();
}, []);

return (
<div>
{items.map((item) => (
<div key={item.id} onClick={(e) => ctx.remove(item, e.currentTarget)}>
Click Me
</div>
))}
</div>
);
}

loading...

However - you may have noticed the layout shift - this is typical of exit animations. The Flip plugin can be used to smooth this out.

In this demo, we're tapping into Flip's onEnter and onLeave to define our animations. To trigger onLeave, we have to set display: none on the elements we want to animate out.

loading...

Custom Hooks

If you find yourself reusing the same logic over and over again, there's a good chance you can extract that logic into a custom hook. Building your own Hooks lets you extract component logic into reusable functions.

Let's take another look at registerEffect() with a custom hook

function useGsapEffect(target, effect, vars) {
const [animation, setAnimation] = useState();

useLayoutEffect(() => {
setAnimation(gsap.effects[effect](target.current, vars));
}, [effect]);

return animation;
}

function App() {
const box = useRef();
const animation = useGsapEffect(box, "spin");

return <Box ref={box}>Hello</Box>;
}

loading...

Here are some custom hooks we've written that we think you may find useful:

useGsapContext

Memoises a GSAP Context instance.

function useGsapContext(scope) {
const ctx = useMemo(() => gsap.context(() => {}, scope), [scope]);
return ctx;
}

Usage:

function App() {
const ctx = useGsapContext(ref);

useLayoutEffect(() => {
ctx.add(() => {
gsap.to(".box", {
x: 200,
stagger: 0.1
});
});
return () => ctx.revert();
}, []);

return (
<div className="app" ref={ref}>
<div className="box">Box 1</div>
<div className="box">Box 2</div>
<div className="box">Box 3</div>
</div>
);
}

See demo on codepen

useStateRef

This hook helps solve the problem of accessing stale values in your callbacks. It works exactly like useState, but returns a third value, a ref with the current state.

function useStateRef(defaultValue) {
const [state, setState] = useState(defaultValue);
const ref = useRef(state);

const dispatch = useCallback((value) => {
ref.current = typeof value === "function" ? value(ref.current) : value;
setState(ref.current);
}, []);

return [state, dispatch, ref];
}

Usage:

const [count, setCount, countRef] = useStateRef(5);
const [gsapCount, setGsapCount] = useState(0);

useLayoutEffect(() => {
const ctx = gsap.context(() => {
gsap.to(".box", {
x: 200,
repeat: -1,
onRepeat: () => setGsapCount(countRef.current)
});
}, app);
return () => ctx.revert();
}, []);

see demo on codepen

useIsomorphicLayoutEffect

You might see a warning if you use server-side rendering (SSR) with useLayoutEffect. You can get around this by conditionally using useEffect during server rendering. This hook will return useLayoutEffect when the code is running in the browser, and useEffect on the server.

caveat:Any "from" state that doesn't match the server-side rendered HTML/CSS content will still suffer from a flash of unstyled content while the JavaScript is being parsed, run and hydrated.

read more about useLayoutEffect and server rendering

const useIsomorphicLayoutEffect = typeof window !== "undefined" 
? useLayoutEffect
: useEffect;

Usage:

function App() {    
const app = useRef();

useIsomorphicLayoutEffect(() => {
const ctx = gsap.context(() => {
gsap.from(".box", { opacity: 0 });
}, app);
return () => ctx.revert();
}, []);

return (
<div className="app" ref={app}>
<div className="box">Box 1</div>
</div>
);
}

see demo on codepen


Reach out!

If there is anything you'd like to see included in this article, or if you have any feedback, please let us know so that we can smooth out the learning curve for future animators.

Good luck with your React projects and happy tweening!