### useGSAP Configuration with All Options Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Example demonstrating the use of all available configuration options for the useGSAP hook. ```typescript useGSAP(() => { gsap.to(".target", { y: 100 }); }, { scope: container, dependencies: [value], revertOnUpdate: true }); ``` -------------------------------- ### TypeScript Configuration Example Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Provides an example of how to use TypeScript with `@gsap/react` by importing the `useGSAPConfig` type for robust type checking of the configuration object. ```typescript import type { useGSAPConfig } from "@gsap/react"; const config: useGSAPConfig = { scope: containerRef, dependencies: [dependency], revertOnUpdate: false }; useGSAP(animationFunction, config); ``` -------------------------------- ### useGSAP Configuration with Dependencies Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Example of using the useGSAP hook with a dependency array to control effect re-runs. ```typescript useGSAP(() => { gsap.to(".box", { x: endX }); }, { dependencies: [endX] }); ``` -------------------------------- ### useGSAP with Dependencies Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md When dependencies are provided, two effect hooks are registered: one for initial setup and another for animations that depend on state changes. The second effect runs after mount and when dependencies change. ```javascript useGSAP(() => { gsap.to(".box", { x }); }, { dependencies: [x] }) ``` -------------------------------- ### Configuration Documentation Source: https://github.com/greensock/react/blob/main/_autodocs/README.md Detailed documentation on the configuration options available for the `useGSAP` hook, including explanations and examples for each property like `scope`, `dependencies`, and `revertOnUpdate`. ```APIDOC ## Configuration Documentation ### Description Detailed documentation covering the `useGSAPConfig` object and its properties, explaining how to configure the `useGSAP` hook's behavior, including selector scoping, dependency management, and cleanup. ### `useGSAPConfig` Object Reference - **`scope`** (ReactRef | string) - Defines the DOM element or selector string to scope animations to. Defaults to the component's root element. - **`dependencies`** (Array) - An array of values. If any value changes, the animations will be recreated. Similar to React's `useEffect` dependency array. - **`revertOnUpdate`** (boolean) - If `true`, animations will be reverted when the component updates or unmounts. Defaults to `true`. ### Configuration Patterns - Scoping animations to specific elements. - Managing animation lifecycle with dependencies. - Controlling animation cleanup behavior. ``` -------------------------------- ### useGSAP with Function and Config Object Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Using useGSAP with both an animation setup function and a configuration object. This allows for defining animations while also specifying scope, dependencies, or revert behavior. ```javascript useGSAP( (context, contextSafe) => { // animation code }, { scope?: ReactRef | Element | string; dependencies?: unknown[]; revertOnUpdate?: boolean; } ) ``` -------------------------------- ### useGSAP with Function Only Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md A simplified usage of useGSAP where only the animation setup function is provided. This defaults to an empty dependency array, meaning the animation runs once on mount and cleans up on unmount. ```javascript useGSAP(() => { // animation code }) ``` -------------------------------- ### Install @gsap/react package Source: https://github.com/greensock/react/blob/main/README.md Command to install the @gsap/react package using npm. This is the first step to using the useGSAP hook in your React project. ```bash npm install @gsap/react ``` -------------------------------- ### Recommended Scoped Animation Setup Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Illustrates a common pattern for using the 'scope' option with a React ref to encapsulate animations within a specific component part. ```javascript const container = useRef(); useGSAP(() => { gsap.from(".item", { opacity: 0, stagger: 0.1 }); gsap.to(".title", { color: "red" }); }, { scope: container // all selectors scoped to container }); return (

Title

Item 1
Item 2
); ``` -------------------------------- ### useGSAP with Function and Dependency Array Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md The useEffect-style usage of useGSAP, where an animation setup function is provided along with a standard React dependency array to control re-runs. ```javascript useGSAP( (context, contextSafe) => { // animation code }, [dependency1, dependency2] ) ``` -------------------------------- ### useGSAP Configuration with Scope Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Example of using the useGSAP hook with a specified scope to limit selector text. ```typescript useGSAP(() => { gsap.from(".item", { opacity: 0 }); }, { scope: containerRef }); ``` -------------------------------- ### Basic Animation Setup with useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Sets up a basic GSAP animation within a React component using the useGSAP hook. The animation targets elements with the class 'box' and runs once after the component mounts. ```javascript import { useRef } from "react"; import gsap from "gsap"; import { useGSAP } from "@gsap/react"; export function BasicAnimation() { const container = useRef(); useGSAP(() => { gsap.from(".box", { opacity: 0, duration: 1 }); }, { scope: container }); return (
Animated element
); } ``` -------------------------------- ### New useGSAP hook basic usage Source: https://github.com/greensock/react/blob/main/README.md Illustrates the basic setup and usage of the useGSAP hook from @gsap/react. It replaces useEffect/useLayoutEffect for cleaner GSAP integration and automatic cleanup. ```javascript import { useRef } from "react"; import gsap from "gsap"; import { useGSAP } from "@gsap/react"; gsap.registerPlugin(useGSAP); // register any plugins, including the useGSAP hook const container = useRef(); useGSAP(() => { // gsap code here... }, { scope: container }); // <-- scope is for selector text (optional) ``` -------------------------------- ### useGSAP Hook Reference Source: https://github.com/greensock/react/blob/main/_autodocs/README.md Provides a complete reference for the main useGSAP hook, including its function signature, parameters, return types, configuration options, callback parameters, and behavior. It also covers static properties, plugin registration, and context-safe functions with numerous usage examples. ```APIDOC ## useGSAP Hook Reference ### Description Complete reference for the main hook, detailing its signature, parameters, return type, and all method variants. Includes configuration options, callback parameters, behavior, cleanup documentation, and extensive usage examples. ### Method Signature ```typescript useGSAP(callback: ContextFunc, config?: useGSAPConfig) ``` ### Parameters #### `callback` (ContextFunc) - Required A function that receives a GSAP context and is used to define animations. #### `config` (useGSAPConfig) - Optional An object to configure the hook's behavior, including scope, dependencies, and cleanup. ### Return Type `useGSAPReturn` - An object containing properties and methods related to the hook's state and control. ### Configuration Options (`useGSAPConfig`) - **`scope`** (ReactRef | string) - Selector scoping for animations. - **`dependencies`** (Array) - Dependency array to trigger re-runs. - **`revertOnUpdate`** (boolean) - Whether to revert animations on update. ### Examples - Basic animation setup - Using dependencies - Advanced scope and context usage ``` -------------------------------- ### useGSAP hook with revertOnUpdate enabled Source: https://github.com/greensock/react/blob/main/README.md Example of configuring useGSAP to revert animations on every update when dependencies change, by setting revertOnUpdate: true in the config object. This ensures animations are reset before re-running. ```javascript useGSAP(() => { // gsap code here... }, { dependencies: [endX], scope: container, revertOnUpdate: true }); ``` -------------------------------- ### Cleanup Function Return Example Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Return a cleanup function from the useGSAP callback to manually handle the removal of animations, event listeners, or other resources. GSAP's context.revert() often handles animation cleanup automatically. ```javascript useGSAP(() => { // setup code const animation = gsap.to(".box", { x: 100 }); // Optional cleanup return () => { animation.kill(); // Optional - context.revert() handles this // Remove event listeners element.removeEventListener("click", handler); // Other cleanup }; }); ``` -------------------------------- ### useGSAP hook with dependencies (simpler syntax) Source: https://github.com/greensock/react/blob/main/README.md Demonstrates an alternative, simpler syntax for useGSAP when only dependencies need to be specified, similar to React's useEffect. The config object syntax is generally preferred for flexibility. ```javascript useGSAP(() => { // gsap code here... }, [endX]); // works, but less flexible than the config object ``` -------------------------------- ### Method Signature: Config as Second Parameter (Dependencies Shorthand) Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Demonstrates using an array as the second parameter to `useGSAP`, which is treated as a shorthand for the `dependencies` option. This simplifies the configuration when only dependencies need to be specified. ```javascript useGSAP( () => { gsap.to(".box", { x: value }); }, [value] // treated as { dependencies: [value] } ); ``` -------------------------------- ### Registering useGSAP Plugin Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Register the useGSAP plugin with GSAP once at the application's start. This makes the hook available for use in all React components. ```javascript import gsap from "gsap"; import { useGSAP } from "@gsap/react"; // Register once at app start gsap.registerPlugin(useGSAP); // Now use throughout your app export function Component() { useGSAP(() => { // useGSAP is ready }); } ``` -------------------------------- ### Equivalent useGSAP Calls Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Shows equivalent ways to call `useGSAP` when no specific dependencies are needed. These all result in the animation running once on mount and never again. ```javascript // These are equivalent: useGSAP(() => {...}); useGSAP(() => {...}, {}); useGSAP(() => {...}, { dependencies: [] }); // All use implicit [] dependency array // All run once on mount, never again ``` -------------------------------- ### Method Signature: Config as First Parameter Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Illustrates calling `useGSAP` with the configuration object as the first parameter, when no animation callback is provided. This is useful for setting up context and safe handlers. ```javascript const { context, contextSafe } = useGSAP({ scope: container, dependencies: [value], revertOnUpdate: true }); ``` -------------------------------- ### Method Signature: Config as Second Parameter with Callback Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Shows the standard way to use `useGSAP` with both an animation callback and a configuration object as the second parameter. This allows for detailed control over animation scope, dependencies, and update behavior. ```javascript useGSAP( () => { gsap.to(".box", { x: 100 }); }, { scope: container, dependencies: [value], revertOnUpdate: true } ); ``` -------------------------------- ### useGSAP hook with dependencies and scope Source: https://github.com/greensock/react/blob/main/README.md Shows how to use the useGSAP hook with a configuration object that includes dependencies and a scope. This allows for more controlled animation updates and element targeting. ```javascript useGSAP(() => { // gsap code here... }, { dependencies: [endX], scope: container}); // config object offers maximum flexibility ``` -------------------------------- ### Default useGSAP Behavior Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Demonstrates the default behavior of `useGSAP` when no configuration object is provided. By default, animations run once on mount and persist across state changes. ```javascript // All defaults useGSAP(() => { gsap.to(".box", { x: 100 }); }); // Equivalent to useGSAP(() => { gsap.to(".box", { x: 100 }); }, { scope: undefined, dependencies: [], revertOnUpdate: false }); ``` -------------------------------- ### Explicit Empty Dependency Array and Omitted Dependencies Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Demonstrates two ways to achieve the default behavior of running an animation once on mount: explicitly passing an empty dependency array or omitting the dependencies option entirely. ```javascript // Explicitly pass empty array (same as default) useGSAP(() => { gsap.to(".box", { x: 100 }); }, { dependencies: [] }); // Or omit dependencies entirely useGSAP(() => { gsap.to(".box", { x: 100 }); }, { scope: container }); ``` -------------------------------- ### Animation with Dependencies using useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Demonstrates how to animate an element based on changing dependencies. The animation re-runs when the 'endX' state changes, ensuring the element moves to the new position. ```javascript export function DynamicAnimation() { const container = useRef(); const [endX, setEndX] = useState(0); useGSAP( () => { gsap.to(".box", { x: endX, duration: 0.5 }); }, { dependencies: [endX], scope: container } ); return (
Move me
); } ``` -------------------------------- ### Using a Registered GSAP Instance Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Demonstrates how to use the useGSAP hook with a GSAP instance that has been explicitly registered. ```javascript import gsap from "gsap"; import { useGSAP } from "@gsap/react"; // If different GSAP version loaded useGSAP.register(gsapInstance); // Now useGSAP uses that instance useGSAP(() => { _gsap.to(".box", { x: 100 }); // Uses registered instance }); ``` -------------------------------- ### Config Object Only for useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Illustrates using useGSAP with only a configuration object, without providing an animation function directly. This is useful for setting up the GSAP context and then triggering animations via other means. ```javascript export function ConfigOnlyExample() { const container = useRef(); const { context, contextSafe } = useGSAP({ scope: container }); const startAnimation = contextSafe(() => { gsap.to(".box", { duration: 1, x: 200 }); }); return (
Target
); } ``` -------------------------------- ### GSAP Debugging with useGSAP Context Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Shows how to use the context and contextSafe utilities from useGSAP for debugging. This includes checking the context instance, manually reverting animations, and verifying the context-safe wrapper. ```javascript const { context, contextSafe } = useGSAP({ scope: container }); // Check if context is created console.log(context); // gsap.Context instance // Manual revert for debugging context.revert(); // Verify context-safe wrapper works const safeHandler = contextSafe(() => { console.log("Handler called"); }); ``` -------------------------------- ### Async Animation Chains with contextSafe Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Demonstrates how to manage sequential asynchronous animations within an event handler using contextSafe, ensuring animations are tracked correctly. ```javascript useGSAP((context, contextSafe) => { const handleClick = contextSafe(async () => { // Animations are tracked even in async flow await gsap.to(".box", { x: 100, duration: 1 }).then(); await gsap.to(".box", { y: 100, duration: 1 }).then(); console.log("Animation sequence complete"); }); element.addEventListener("click", handleClick); return () => element.removeEventListener("click", handleClick); }); ``` -------------------------------- ### Managing Animation Updates with Dependencies Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Shows how to use the 'dependencies' array in useGSAP to control when animations re-run, similar to useEffect. An empty array or omitted dependencies run the effect once on mount. ```javascript // Run once on mount useGSAP(() => { gsap.from(".box", { opacity: 0 }); }); // Re-run when endX changes const [endX, setEndX] = useState(0); useGSAP(() => { gsap.to(".box", { x: endX }); }, { dependencies: [endX] }); // Re-run when multiple dependencies change const [rotation, setRotation] = useState(0); useGSAP(() => { gsap.to(".box", { rotation }); }, { dependencies: [rotation, scale] }); ``` -------------------------------- ### useGSAP.headless Property Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Illustrates the useGSAP.headless property, indicating server-side rendering compatibility. ```javascript useGSAP.headless = true; ``` -------------------------------- ### useGSAP with contextSafe in Callback Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Demonstrates using contextSafe directly within the useGSAP callback to wrap event listeners, ensuring proper context management for animations triggered by events. ```typescript useGSAP((context, contextSafe) => { const handleClick = contextSafe(() => { gsap.to(".target", { rotation: 180 }); }); element.addEventListener("click", handleClick); return () => { element.removeEventListener("click", handleClick); }; }); ``` -------------------------------- ### useGSAP Callback with Context and Cleanup Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Demonstrates the use of the callback function within useGSAP, which receives GSAP context and a contextSafe wrapper. It includes creating an animation and wrapping an event handler, with an optional cleanup function. ```javascript useGSAP((context, contextSafe) => { // context — gsap.Context instance // contextSafe — Function wrapper for safe callbacks // Create animation gsap.to(".box", { x: 100 }); // Wrap event handler const onClick = contextSafe(() => { gsap.to(".btn", { scale: 0.9 }); }); // Optional: return cleanup function return () => { // cleanup code }; }); ``` -------------------------------- ### useGSAP with No Dependencies Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Use this pattern when the animation should run only once after the component mounts. It registers a single effect hook that runs once and returns a cleanup function. ```javascript useGSAP(() => { gsap.to(".box", { x: 100 }); }) ``` -------------------------------- ### Object References in useGSAP Dependencies (Solution 1) Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Provides a solution to the object reference problem by memoizing the configuration object using `useMemo`. This ensures the object reference remains stable across renders. ```javascript // SOLUTION 1: Memoize the object const config = useMemo(() => ({ x: 100, duration: 1 }), []); useGSAP(() => { gsap.to(".box", config); }, { dependencies: [config] }); ``` -------------------------------- ### Import Methods for @gsap/react Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Demonstrates various ways to import the useGSAP hook from the @gsap/react library depending on your module system. ```javascript // CommonJS const { useGSAP } = require("@gsap/react"); ``` ```javascript // ES Module import { useGSAP } from "@gsap/react"; ``` ```typescript // TypeScript import { useGSAP } from "@gsap/react"; import type { useGSAPReturn, useGSAPConfig } from "@gsap/react"; ``` -------------------------------- ### useGSAP.register() Implementation Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Shows how to register a specific GSAP instance with the useGSAP hook, useful when multiple GSAP versions are present. ```javascript useGSAP.register = core => { _gsap = core; }; ``` -------------------------------- ### Accessing contextSafe Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Demonstrates two methods for accessing the `contextSafe` function provided by the `useGSAP` hook: directly from the returned object and from the callback parameters. ```APIDOC ## Accessing contextSafe ### Description Illustrates how to access the `contextSafe` function, which ensures that animations are created within the GSAP context and are properly cleaned up. ### Method 1: From the returned object This method is suitable for event handlers defined outside the `useGSAP` hook. ```javascript const { contextSafe } = useGSAP({ scope: container }); const onClick = contextSafe(() => { gsap.to(".element", { rotation: 180 }); }); ``` ### Method 2: From the callback parameters This method is useful for event handlers defined inside the `useGSAP` hook's callback. ```javascript useGSAP((context, contextSafe) => { element.addEventListener("click", contextSafe(() => { gsap.to(element, { y: 100 }); })); }); ``` ``` -------------------------------- ### Minimal useGSAP Animation Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md A basic useGSAP animation that runs once on component mount. No specific dependencies or scope are provided. ```javascript useGSAP(() => { gsap.to(".box", { x: 100 }); }); ``` -------------------------------- ### Correct useGSAP Configuration Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Pass configuration options as an object to useGSAP for proper scope and dependency management. Avoid passing a dependency array directly as the second argument. ```javascript // ❌ WRONG - dependency array used as dependencies config useGSAP(() => {...}, [ref, x]); // Runs on every change, no scope // ✅ CORRECT - use config object for scope + dependencies useGSAP(() => {...}, { scope: ref, dependencies: [x] }); ``` -------------------------------- ### useGSAP with Config Object and Scope Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Demonstrates using useGSAP with a configuration object that specifies a scope. This limits GSAP selectors to descendants of the provided element or ref. ```javascript useGSAP({ scope: containerRef }) ``` -------------------------------- ### isConfig() Helper Function Logic Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Explains the logic of the internal isConfig helper function used to differentiate configuration objects from callback functions. ```javascript const isConfig = value => value && !Array.isArray(value) && typeof(value) === "object" ``` -------------------------------- ### Internal State Management with useRef Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Demonstrates how the useGSAP hook utilizes `useRef` to manage internal state, including component mount status, GSAP context, and a context-safe function. ```javascript const mounted = useRef(false); const context = useRef(_gsap.context()); const contextSafe = useRef((func) => context.current.add(null, func)); ``` -------------------------------- ### useGSAP with Config Object Only Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Invoking useGSAP using only a configuration object. This is useful for setting up scope, dependencies, or revert behavior without immediately defining animations. ```javascript useGSAP({ scope?: ReactRef | Element | string; dependencies?: unknown[]; revertOnUpdate?: boolean; }) ``` -------------------------------- ### useGSAP.register() Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Allows explicit registration of a GSAP core instance with the hook, useful when multiple GSAP versions might be present. ```APIDOC ## useGSAP.register() ### Description Allows the hook to use a specific GSAP instance if multiple versions are loaded in the same application. This is useful for managing dependencies in complex projects. ### Signature ```typescript useGSAP.register(core: typeof gsap): void ``` ### Parameters - **core** (typeof gsap) - Required - The GSAP core instance to register. ### Purpose To ensure the hook utilizes the intended GSAP core instance, preventing potential conflicts. ### Implementation Example ```javascript import gsap from 'gsap'; import { useGSAP } from '@gsap/react'; // Register a specific GSAP instance useGSAP.register(gsap); ``` ``` -------------------------------- ### useGSAP.register() Method Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Register the useGSAP plugin with GSAP. This can be done using either gsap.registerPlugin or useGSAP.register. ```javascript gsap.registerPlugin(useGSAP); // OR useGSAP.register(gsap); ``` -------------------------------- ### useGSAP hook method signatures Source: https://github.com/greensock/react/blob/main/README.md Outlines the various available method signatures for the useGSAP hook, including the most flexible config object, the useEffect-like syntax, and the context/contextSafe return. ```javascript // config object for defining things like scope, dependencies, and revertOnUpdate (most flexible) useGSAP(func, config); // exactly like useEffect() useGSAP(func); useGSAP(func, dependencies); // primarily for event handlers and other external uses (read about contextSafe() below) const { context, contextSafe } = useGSAP(config); ``` -------------------------------- ### useGSAP Return Object Usage Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Demonstrates how to access and use the context and contextSafe properties returned by the useGSAP hook. ```typescript const { context, contextSafe } = useGSAP({ scope: container }); // Access context directly context.revert(); // manually revert all animations // Use contextSafe for event handlers const handleClick = contextSafe(() => { gsap.to(".target", { rotation: 360 }); }); ``` -------------------------------- ### TypeScript Type Checking for useGSAPConfig Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Shows how to use TypeScript to enforce type safety for useGSAP configuration objects and return types, including contextSafe. ```typescript import type { useGSAPConfig, ContextSafeFunc } from "@gsap/react"; import gsap from "gsap"; // Config type checking const config: useGSAPConfig = { scope: ref, dependencies: [value], revertOnUpdate: true }; // Return type is inferred const result = useGSAP(() => { gsap.to(".box", { x: 100 }); }, config); // Type-safe contextSafe const safeHandler: ContextSafeFunc = result.contextSafe; // Function signature is preserved const onClick = safeHandler((e: React.MouseEvent) => { gsap.to(".target", { rotation: 360 }); }); // onClick has type: (e: React.MouseEvent) => void ``` -------------------------------- ### useGSAP with revertOnUpdate = true Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Setting `revertOnUpdate: true` forces cleanup and animation restarts on every dependency change. The initial mount effect is skipped, and cleanup occurs on each change, not just unmount. ```javascript useGSAP(() => { gsap.to(".box", { x }); }, { dependencies: [x], revertOnUpdate: true }) ``` -------------------------------- ### Managing Dependencies in useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Avoid recreating functions on every render by defining them outside the `useGSAP` call or by using `useCallback`. This is crucial for performance and correct dependency tracking. ```javascript // ❌ WRONG: function recreated every render useGSAP( () => { gsap.to(".box", { x: 100 }); }, { dependencies: [() => console.log("done")] } ); // ✅ CORRECT: use useCallback or move outside const onDone = useCallback(() => console.log("done"), []); useGSAP( () => { gsap.to(".box", { x: 100 }); }, { dependencies: [onDone] } ); ``` -------------------------------- ### Function References in useGSAP Dependencies (Solution) Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Presents the solution for function references in dependencies by using `useCallback`. This memoizes the function, ensuring its reference remains stable across renders and preventing unnecessary animation re-runs. ```javascript // SOLUTION: Use useCallback const onComplete = useCallback(() => console.log("done"), []); useGSAP(() => { gsap.to(".box", { duration: 1, onComplete }); }, { dependencies: [onComplete] }); ``` -------------------------------- ### Registering useGSAP with GSAP Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Shows how to register the useGSAP hook as a GSAP plugin. This is necessary when you need to use a specific GSAP instance or ensure proper plugin loading. ```typescript import gsap from "gsap"; import { useGSAP } from "@gsap/react"; gsap.registerPlugin(useGSAP); ``` -------------------------------- ### Scope Performance Comparison Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Illustrates the performance benefits of using a single scope for GSAP selector queries compared to managing multiple individual refs. ```javascript // ✅ FASTER: Single scope, GSAP optimizes selector queries useGSAP(() => { gsap.from(".item", { opacity: 0 }); // Uses selector cache }, { scope: container }); // ❌ SLOWER: Multiple refs require individual animations const refs = useRefs(items); // Creates many refs items.forEach((item, i) => { gsap.from(refs[i], { opacity: 0 }); }); ``` -------------------------------- ### Old useEffect/useLayoutEffect approach for GSAP Source: https://github.com/greensock/react/blob/main/README.md Demonstrates the traditional method of using useEffect or useLayoutEffect with gsap.context() for managing GSAP animations and cleanup in React. This approach requires manual context creation and reversion. ```javascript import { useEffect, useLayoutEffect, useRef } from "react"; import gsap from "gsap"; // for server-side rendering apps, useEffect() must be used instead of useLayoutEffect() const useIsomorphicLayoutEffect = (typeof window !== "undefined") ? useLayoutEffect : useEffect; const container = useRef(); useIsomorphicLayoutEffect(() => { const ctx = gsap.context(() => { // gsap code here... }, container); // <-- scope for selector text return () => ctx.revert(); // <-- cleanup }, []); // <-- empty dependency Array so it doesn't get called on every render ``` -------------------------------- ### Config Object Only with contextSafe Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Set up the GSAP context without an immediate animation callback. Use `contextSafe()` to create event handlers that can trigger GSAP animations within the defined scope. ```javascript const container = useRef(); const { contextSafe } = useGSAP({ scope: container }); const handleHover = contextSafe(() => { gsap.to(".card", { scale: 1.05, duration: 0.2 }); }); return (
Hover me
); ``` -------------------------------- ### Reactive Animation with Dependencies Source: https://github.com/greensock/react/blob/main/_autodocs/INDEX.md Implement animations that react to state changes by providing dependencies to useGSAP. Set revertOnUpdate to true to ensure animations reset on each update. Requires useState and useRef. ```javascript export function Counter() { const [count, setCount] = useState(0); const container = useRef(); useGSAP(() => { gsap.to(".number", { innerHTML: count, duration: 0.5 }); }, { scope: container, dependencies: [count], revertOnUpdate: true }); return (
{count}
); } ``` -------------------------------- ### useGSAP.headless Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md A static property indicating whether the hook can function in a server-side rendering (SSR) environment without a `window` object. ```APIDOC ## useGSAP.headless ### Description Indicates to GSAP that this plugin can function without `window` being defined, making it safe for server-side rendering (SSR). ### Type `boolean` ### Value `true` ### Purpose To allow GSAP animations or related logic to be processed on the server without errors, ensuring compatibility with SSR frameworks. ``` -------------------------------- ### Return Object Methods Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md The return object from useGSAP provides context methods like add() and revert(), and a contextSafe function to wrap other functions. ```javascript const { context, contextSafe } = useGSAP(...); // context methods context.add(callback, scope); // Add callback to context context.revert(); // Revert all GSAP objects in context // contextSafe function const safeFunc = contextSafe(myFunction); safeFunc(); // GSAP objects created here are tracked ``` -------------------------------- ### Click Handler Animation Pattern Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Implements a click handler that scales an element up and then back down. The handler is made context-safe using useGSAP's return object. ```javascript const { contextSafe } = useGSAP({ scope: container }); const handleClick = contextSafe(() => { gsap.to(element, { duration: 0.3, scale: 1.1 }).then(() => { gsap.to(element, { scale: 1 }); }); }); return ; ``` -------------------------------- ### Basic useGSAP Animation Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Set up a GSAP animation within a React component using the useGSAP hook. The animation will be automatically managed by the GSAP context. ```typescript useGSAP((context) => { gsap.to(".box", { duration: 1, x: 100 }); }); ``` -------------------------------- ### Restarting Animation on Dependency Change Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Configure useGSAP to restart animations when dependencies change by setting `revertOnUpdate` to `true`. This ensures animations reflect the latest state. ```javascript // ✅ If you want animation to restart on dependency change: useGSAP(() => { gsap.to(".box", { x: endX }); }, { dependencies: [endX], revertOnUpdate: true // Add this! }); ``` -------------------------------- ### Common GSAP Animation Methods in React Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Demonstrates animating elements to target values, from values, sequencing with timelines, repeating/yoyoing animations, staggering multiple elements, and using scope for selectors within the useGSAP hook. ```javascript useGSAP(() => { // Animate to target values gsap.to(".box", { duration: 1, x: 100, opacity: 0.5 }); // Animate from values gsap.from(".box", { opacity: 0, y: -20 }); // Timeline for sequencing const tl = gsap.timeline(); tl.to(".box1", {...}).to(".box2", {...}, 0); // Repeat/Yoyo gsap.to(".box", { y: 100, repeat: -1, yoyo: true }); // Stagger multiple elements gsap.to(".item", { x: 100, stagger: 0.1 }); // Use scope for selectors gsap.to(".item", { x: 100 }); // scoped if scope defined }); ``` -------------------------------- ### Manual Cleanup with context.revert() Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md While useGSAP automatically handles cleanup, you can manually revert animations, ScrollTriggers, and DOM modifications using the context object if needed. ```javascript const { context } = useGSAP(); // Later, if needed: context.revert(); ``` -------------------------------- ### Manual Revert Animation Source: https://github.com/greensock/react/blob/main/_autodocs/INDEX.md Demonstrates how to manually revert all animations managed by the GSAP context. This is useful for explicit cleanup. ```javascript const { context } = useGSAP(); context.revert(); // reverts all animations ``` -------------------------------- ### Object References in useGSAP Dependencies (Solution 2) Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Offers an alternative solution by using primitive values directly in the dependency array instead of an object reference. This avoids issues with object recreation. ```javascript // SOLUTION 2: Use primitive values const x = 100; useGSAP(() => { gsap.to(".box", { x, duration: 1 }); }, { dependencies: [x] }); ``` -------------------------------- ### Automatic Cleanup Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Explains the automatic cleanup process handled by the `useGSAP` hook, which reverts animations, ScrollTriggers, and DOM modifications upon component unmount. ```APIDOC ## Cleanup ### Description The `useGSAP` hook automatically returns a cleanup function from the React effect. This function calls `context.revert()` to manage animations and DOM states. ### Actions Performed by Cleanup: - Kills all animations created within the context. - Removes all ScrollTriggers created within the context. - Reverts any DOM modifications made by GSAP. - Restores initial inline styles. - Clears internal context tracking. ### Manual Cleanup (Optional) You can manually trigger the cleanup process if needed: ```javascript const { context } = useGSAP(); // Later, if needed: context.revert(); ``` ``` -------------------------------- ### Import Statement for useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Import the useGSAP hook and gsap, then register the hook as a GSAP plugin. This is required before using useGSAP. ```javascript import { useGSAP } from "@gsap/react"; import gsap from "gsap"; // Register the hook as a GSAP plugin gsap.registerPlugin(useGSAP); ``` -------------------------------- ### useGSAP Hook Signatures Source: https://github.com/greensock/react/blob/main/_autodocs/INDEX.md The core export, useGSAP, acts as a drop-in replacement for React's useEffect() and useLayoutEffect(). It supports various signature patterns for configuration and animation functions. ```APIDOC ## useGSAP Hook Signatures The core export. A drop-in replacement for React's `useEffect()` and `useLayoutEffect()`. **Signatures**: ```typescript // Config object only useGSAP(config: useGSAPConfig): useGSAPReturn // Function with config useGSAP(func: ContextFunc, config: useGSAPConfig): useGSAPReturn // Function with dependencies (useEffect-style) useGSAP(func: ContextFunc, dependencies: unknown[]): useGSAPReturn // Function only (empty dependencies) useGSAP(func: ContextFunc): useGSAPReturn ``` **Returns**: ```typescript { context: gsap.Context, // GSAP context managing cleanups contextSafe: Function // Wrapper for context-safe callbacks } ``` **Configuration**: ```typescript { scope?: ReactRef | Element | string; // Scope for selectors dependencies?: unknown[]; // Dependency array revertOnUpdate?: boolean; // Revert on each update } ``` **Callback Function** The animation setup function receives parameters: ```typescript (context: gsap.Context, contextSafe?: ContextSafeFunc) => Function | void ``` Returns optional cleanup function, similar to useEffect cleanup. ``` -------------------------------- ### useGSAP.headless Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md A boolean property that indicates if the environment is server-side rendering (SSR) safe. ```APIDOC ## useGSAP.headless ### Description A boolean property that indicates if the environment is server-side rendering (SSR) safe. ### Usage ```javascript if (useGSAP.headless) { // SSR-safe logic } ``` ``` -------------------------------- ### Enabling Headless Mode Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Sets the headless property to true, enabling the GSAP plugin to work in Node.js/SSR environments without requiring a window object. ```javascript useGSAP.headless = true ``` -------------------------------- ### Context Object Methods Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md The `context` object returned by `useGSAP` provides methods to manage GSAP animations within the component's lifecycle. ```APIDOC ## Context Object Methods ### Description Methods available on the `context` object returned by `useGSAP` for managing animations. ### Methods - `context.add(callback, scope)`: - Adds a GSAP animation or callback to the context. Ensures it's included in cleanup. - `callback`: The function to add. - `scope`: Optional scope for the callback. - `context.revert()`: - Reverts all GSAP objects (animations, tweens, etc.) that were added to this context. This is typically called automatically by React when the component unmounts or dependencies change if `revertOnUpdate` is true. ### Example Usage ```javascript const { context } = useGSAP(); // Add a tween to the context context.add(() => { gsap.to(".element", { x: 100 }); }); // Manually revert (usually not needed) // context.revert(); ``` ``` -------------------------------- ### useIsomorphicLayoutEffect Selection Logic Source: https://github.com/greensock/react/blob/main/_autodocs/module-reference.md Details the logic for selecting between useLayoutEffect and useEffect based on the environment (browser vs. SSR). ```javascript let useIsomorphicLayoutEffect = typeof document !== "undefined" ? useLayoutEffect : useEffect ``` -------------------------------- ### ReactRef Usage with useRef Source: https://github.com/greensock/react/blob/main/_autodocs/types.md Shows how to create and use React refs with the useRef hook in React, and how they can be passed to useGSAP. ```typescript import { useRef } from "react"; const container = useRef(); // creates ReactRef const element = useRef(null); // creates ReactRef useGSAP(() => { // container.current is the DOM element gsap.to(container.current, { opacity: 0.5 }); }, { scope: container }); ``` -------------------------------- ### SSR Hydration Safety with useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/advanced-patterns.md Shows how `useGSAP` automatically handles Server-Side Rendering (SSR) by using `useEffect` on the server and `useLayoutEffect` on the client. This prevents hydration mismatches and ensures animations work correctly on the client. ```javascript // ✅ SAFE - useGSAP automatically handles SSR export function AnimatedComponent() { useGSAP(() => { gsap.to(".box", { x: 100 }); }); // On server: useEffect runs (animations skip) // On client: useLayoutEffect runs (animations work) // Result: No hydration mismatch } ``` -------------------------------- ### useGSAP Configuration Interface Source: https://github.com/greensock/react/blob/main/_autodocs/configuration.md Defines the structure for the useGSAP configuration object, including optional properties for scope, dependencies, and revertOnUpdate. ```typescript interface useGSAPConfig { scope?: ReactRef | Element | string; dependencies?: unknown[]; revertOnUpdate?: boolean; } ``` -------------------------------- ### Context-Safe Function for Event Handlers Source: https://github.com/greensock/react/blob/main/_autodocs/INDEX.md Shows how to wrap event handlers with `contextSafe()` to ensure animations created within them are tracked and reverted by the GSAP context. This is crucial for proper cleanup. ```javascript const { contextSafe } = useGSAP({ scope: container }); // ✅ Context-safe - animations tracked for cleanup const handleClick = contextSafe(() => { gsap.to(".target", { rotation: 360 }); }); // ❌ Not context-safe - animations NOT tracked const badHandler = () => { gsap.to(".target", { rotation: 360 }); }; ``` -------------------------------- ### Revert on Update Pattern with useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/api-reference/useGSAP.md Implements the 'revertOnUpdate: true' pattern, causing the animation to be completely reverted and re-created on every dependency change. This is useful for animations that need to reset and restart based on dynamic values. ```javascript export function RevertOnUpdateExample() { const container = useRef(); const [count, setCount] = useState(0); useGSAP( () => { // This entire animation will be reverted and re-created // every time 'count' changes gsap.to(".box", { x: count * 50, duration: 0.5 }); }, { dependencies: [count], revertOnUpdate: true, scope: container } ); return (
Responsive
); } ``` -------------------------------- ### Register useGSAP plugin Source: https://github.com/greensock/react/blob/main/README.md Code snippet showing how to register the useGSAP hook as a GSAP plugin. This should typically be done at the top of your code, below imports. ```javascript gsap.registerPlugin(useGSAP); ``` -------------------------------- ### Type Annotations with useGSAP Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md Utilize TypeScript for type safety when configuring and using the useGSAP hook. This includes defining configuration objects and handling the return values. ```typescript import { useGSAP } from "@gsap/react"; import type { useGSAPReturn, useGSAPConfig, ContextSafeFunc } from "@gsap/react"; const config: useGSAPConfig = { scope: containerRef, dependencies: [value], revertOnUpdate: false }; const result: useGSAPReturn = useGSAP(() => { gsap.to(".box", { x: 100 }); }, config); const contextSafe: ContextSafeFunc = result.contextSafe; ``` -------------------------------- ### useGSAP() Hook Signature Source: https://github.com/greensock/react/blob/main/_autodocs/quick-reference.md The useGSAP hook returns an object containing context and contextSafe. It accepts a callback function and optional dependencies or a configuration object. ```typescript // Returns object with context and contextSafe const { context, contextSafe } = useGSAP(callback, dependencies) ```