fn

useAnimate

v0.0.14testeddemo

Reactive Web Animations API wrapper for a single element. Exposes imperative controls (play, pause, reverse, finish, cancel) alongside reactive state (playState, currentTime, playbackRate, ...). The reactive state is synced via requestAnimationFrame only while the animation is running, so an idle animation costs nothing. SSR-safe: nothing touches the DOM until the element resolves.

Examples

ts
const el = useTemplateRef<HTMLElement>('el');
const { playState, play, pause } = useAnimate(
  el,
  [{ transform: 'rotate(0)' }, { transform: 'rotate(360deg)' }],
  { duration: 1000, iterations: Infinity },
);
ts
// Shorthand: third argument is the duration in milliseconds
useAnimate(el, { opacity: [0, 1] }, 500);

Demo

Loading demo…

Signature

ts
export function useAnimate(
  target: MaybeComputedElementRef,
  keyframes: UseAnimateKeyframes,
  options?: number | UseAnimateOptions,
): UseAnimateReturn{ ... }

Parameters

ParameterTypeDescription
targetMaybeComputedElementRefElement to animate (reactive ref, getter, or element)
keyframesUseAnimateKeyframesKeyframes to animate, reactive
options?number | UseAnimateOptionsDuration in ms, or full options object

Returns

UseAnimateReturnSupport flag, the Animation instance, controls, and reactive state
PropertyTypeDescription
isSupportedReadonly<Ref<boolean>>Whether the Web Animations API is supported in the current environment
animateShallowRef<Animation | undefined>The underlying Animation instance, or undefined before it is created
play() => voidStart or resume the animation
pause() => voidSuspend playback of the animation
reverse() => voidReverse the playback direction of the animation
finish() => voidSeek the animation to the end of its active duration
cancel() => voidAbort the animation, clearing its effects
pendingComputedRef<boolean>Whether the animation is currently waiting for an asynchronous operation
playStateComputedRef<AnimationPlayState>The current playback state of the animation
replaceStateComputedRef<AnimationReplaceState>The current replace state of the animation
startTimeWritableComputedRef<CSSNumberish | number | null>The scheduled time at which the animation should begin (writable)
currentTimeWritableComputedRef<CSSNumberish | null>The current time value of the animation in milliseconds (writable)
timelineWritableComputedRef<AnimationTimeline | null>The timeline associated with the animation (writable)
playbackRateWritableComputedRef<number>The playback rate of the animation (writable)