Ani
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 * as a from "@freestylejs/ani-core";
import { useAni, useTimeline } from "@freestylejs/ani-react";

const Counter = () => {
  // 1. Own a timeline for the lifetime of the component.
  const myTimeline = useTimeline(() =>
    a.rafTimeline(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.

Behavior

  • initialValue is read on the first render only. It is the value shown until the timeline produces one, and the value rendered on the server.
  • The hook follows timeline identity changes: it unsubscribes from the old timeline and shows the new timeline's current value.
  • The returned controller is stable per timeline.
  • It subscribes after mount, so server rendering retains nothing. See SSR.
  • It never disposes the timeline you pass.

When to Use

  • Do use useAni when 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 useAni for high-frequency style updates (like transform or opacity). Use useAniRef for those cases to avoid performance overhead.

API Reference

NameTypeDescription
timelineRafTimeline<G>The timeline to read.
initialValueAniGroup<G>Value before the timeline has one (first render only).

Returns readonly [value, controller]: the current AniGroup<G> and a stable RafTimeline<G> controller.

  • useAniRef - For performance-critical animations that write directly to the DOM.
  • rafTimeline - The core controller that this hook subscribes to.