Ani
Svelte

useAniStates

A reactive primitive for managing and transitioning between multiple animation states.

This primitive is a Svelte-specific wrapper around the core createStates function. It's designed for components with multiple, distinct visual states (e.g., idle, hover, active) and provides a simple, reactive API to manage transitions between them.

Example

<script>
  import { a } from "@freestylejs/ani-core";
  import { useAniStates } from "@freestylejs/ani-svelte";

  // 1. Define the animations for each state.
  const animations = {
    idle: a.ani({ to: { scale: 1, opacity: 0.7 }, duration: 0.5 }),
    hover: a.ani({ to: { scale: 1.1, opacity: 1 }, duration: 0.3 }),
  };

  // 2. Use the primitive to create the state machine. It returns the action,
  // reactive stores for state info, and a function to transition.
  const [refAction, { timeline }, transitionTo] = useAniStates({
    initial: "idle",
    initialFrom: { scale: 1, opacity: 0.7 },
    states: animations,
  });
</script>

<button
  use:refAction
  on:mouseenter={() => transitionTo("hover")}
  on:mouseleave={() => transitionTo("idle")}
  style="opacity: 0.7; scale: 1"
  class="rounded-md bg-blue-500 px-4 py-2 transition-all"
>
  Hover Me
</button>

Usage & Concepts

Overview

The useAniStates primitive simplifies stateful animation logic in Svelte. It manages the active animation state and its corresponding timeline, automatically handling seamless transitions. When you call transitionTo, it uses the current animation's value as the starting point for the next animation, ensuring smooth, interruptible effects.

When to Use

  • Do use useAniStates for components with a finite number of visual states, such as buttons, interactive cards, or navigation items.
  • Do combine useAniStates with useAniRef for high-performance style animations that react to state changes.
  • Don't create the states object inside a reactive computation without memoization, as this can lead to unexpected behavior.
  • createStates - The core function that this primitive is built upon.
  • useAniRef - To apply the stateful animations to the DOM.
  • useAni - To reactively read the animation values from the active timeline.