React
useAni
A reactive hook that syncs an animation's state with a component's render cycle.
This hook subscribes to a timeline's state and triggers a component re-render on each animation frame, making it ideal for animations that drive UI content.
Example
import { a } from "@freestylejs/ani-core";
import { useAni } from "@freestylejs/ani-react";
import { useMemo } from "react";
const Counter = () => {
// 1. Define the animation and create a timeline instance.
const myTimeline = useMemo(
() => a.timeline(a.ani({ to: { count: 100 }, duration: 5 })),
[]
);
// 2. Use the hook to get the reactive value and the controller.
const [value, controller] = useAni(myTimeline, { count: 0 });
// 3. The component re-renders on each frame, updating the display.
return (
<div>
<h1>Counter: {Math.round(value.count)}</h1>
<button onClick={() => controller.play({ from: { count: 0 } })}>
Start
</button>
</div>
);
};Usage & Concepts
Overview
The useAni hook acts as a bridge between the @freestylejs/ani-core engine and React's render cycle. It uses React's useSyncExternalStore internally to efficiently subscribe to the external animation state. On each frame, it provides the updated animation value, triggering a re-render.
When to Use
- Do use
useAniwhen the animated values need to be part of React's state and render flow. - Do use it for animations that affect text content, attributes, or props of other components.
- Don't use
useAnifor high-frequency style updates (liketransformoropacity). UseuseAniReffor those cases to avoid performance overhead.
API Reference
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
timeline | Timeline<G> | The timeline instance to subscribe to. | — |
initialValue | AniGroup<G> | The value to use before the animation starts. | — |
Return Value
The hook returns a readonly tuple with the following structure:
| Index | Type | Description |
|---|---|---|
[0] | AniGroup<G> | The current, reactive state of the animation. |
[1] | TimelineController<G> | The controller object for the timeline (play, pause, etc.). |
Type Definitions
import { Groupable, Timeline, AniGroup, TimelineController } from '@freestylejs/ani-core';
function useAni<G extends Groupable>(
timeline: Timeline<G>,
initialValue: AniGroup<G>
): readonly [AniGroup<G>, TimelineController<G>];