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.dynamicTimeline(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.