Ensure callbacks are context-safe with contextSafe()
mainFunctions executed after the initial useGSAP() call (like click handlers, setTimeout, or event listeners) are not automatically tracked by the GSAP context. To ensure animations created inside these functions are properly scoped and automatically cleaned up when the component unmounts, you must wrap them in contextSafe().
You can access contextSafe in two ways:
- From the returned object: When calling
useGSAPwith a config object. - As a second argument: Inside the
useGSAP()callback function.
Note: If you add event listeners manually inside useGSAP, remember to remove them in the cleanup function returned by the hook.
// Method 1: Using the returned object property
const container = useRef();
const { contextSafe } = useGSAP({ scope: container });
const onClickGood = contextSafe(() => {
gsap.to(".good", { rotation: 180 });
});
// Method 2: Using the 2nd argument inside useGSAP
useGSAP((context, contextSafe) => {
const onClickGood = contextSafe(() => {
gsap.to(".good", { rotation: 180 });
});
goodRef.current.addEventListener("click", onClickGood);
return () => {
goodRef.current.removeEventListener("click", onClickGood);
};
}, { scope: container });