Ani
React

useAniRef

A performant hook that animates a DOM element through a ref, bypassing React renders.

useAniRef binds an element to a timeline with timeline.bind. On each frame the core writes the changed style declarations straight to the element, so the component does not render per frame.

Example

import * as a from "@freestylejs/ani-core";
import { useAniRef, useTimeline } from "@freestylejs/ani-react";

const InteractiveBox = () => {
  // 1. The component owns the timeline.
  const timeline = useTimeline(() =>
    a.rafTimeline(a.ani({ to: { translateX: 500, rotate: 360 }, duration: 2 }))
  );

  // 2. `ref` binds the element, `style` is the initial inline style.
  const { ref, style } = useAniRef(timeline, {
    initialValue: { translateX: 0, rotate: 0 },
  });

  // 3. The component renders once. Frames are written to the DOM.
  return (
    <>
      <button onClick={() => timeline.play({ from: { translateX: 0, rotate: 0 } })}>
        Play
      </button>
      <div ref={ref} style={style} className="size-24 bg-blue-500" />
    </>
  );
};

Usage & Concepts

Overview

Values are converted to CSS by the core ({ translateX: 100 } becomes transform: translateX(100px), see styles) and written only when a declaration changed. The hook does no writing itself.

DOM events are not part of this hook. Use React's own onClick, onPointerMove and friends and call the timeline from there.

Lifecycle

  • Stable ref. The callback keeps its identity while timeline is the same. Pass it to a child component and it still binds the element that child renders, even when the element mounts later.
  • Attach and detach. Attaching an element binds it and writes the timeline's current value at once. Detaching it (conditional rendering) or unmounting unbinds it.
  • Timeline changes. A new timeline rebinds the current element to it.
  • Stable style. style comes from initialValue on the first render and keeps its identity. Re-rendering never resets an animated style. Without initialValue it is undefined.
  • Server rendering. style is rendered into the HTML, so the first paint already shows the initial value. Nothing subscribes during server rendering.
  • Ownership. The hook never disposes the timeline you pass. Create it with useTimeline, or dispose it yourself.

API Reference

NameTypeDescription
timelineRafTimeline<G>The timeline that drives the element.
options.initialValueAniGroup<G>(Optional) Value of the initial inline style.
options.resolverResolver<Record<string, number>>(Optional) Maps values to style declarations. Used for style and for every write. Read when an element attaches.

Returns { ref, style }.

  • useTimeline - Creates and disposes the timeline.
  • useAniGroup - The same for a list of elements.
  • useAni - For values that must render as content.