Ani
React

useAniStates

A hook that owns a state machine, animates an element between its states and re-renders on transitions.

useAniStates wraps the core createStates. It is for components with a few distinct visual states (idle, hover, active). The machine writes the element through machine.bind, and state re-renders the component once per transition.

Example

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

const StateButton = () => {
  const { ref, style, state, transitionTo } = useAniStates({
    initial: "idle",
    initialValue: { opacity: 0.7, scale: 1 },
    states: {
      idle: a.ani({ to: { scale: 1, opacity: 0.7 }, duration: 0.5 }),
      hover: a.ani({ to: { scale: 1.25, opacity: 1 }, duration: 0.4 }),
    },
  });

  return (
    <button
      ref={ref}
      style={style}
      data-state={state}
      onMouseEnter={() => transitionTo("hover")}
      onMouseLeave={() => transitionTo("idle")}
    >
      Hover Me
    </button>
  );
};

Lifecycle

  • Owns its machine. The hook creates it and disposes it on unmount, which stops any running timeline. StrictMode's synchronous effect replay keeps the same machine (disposal is deferred one microtask and cancelled by the reconnect); a hide longer than a microtask disposes it and the reveal re-creates it.
  • Props are read once. states, initial, initialValue and clock are read on the first render only, like the initial value of useState. To start from different props, remount with a key.
  • Rendering. state is the machine's state and re-renders on transitions, also on transitions made directly on machine. Frames never render.
  • Stable transitionTo. It keeps its identity across renders and returns the promise of the run ('ended', 'interrupted', ...). An unknown state throws a RangeError and changes nothing. After unmount it resolves 'disposed'.
  • Stable ref. Attaching an element binds it to the machine and writes the current value. The binding follows every later timeline.
  • Server rendering. style is built from initialValue and rendered into the HTML. Nothing subscribes.

API Reference

NameTypeDescription
configStateProps & { resolver? }initial, initialValue, states, optional clock, optional style resolver. See createStates.

Returns:

MemberDescription
refElement ref.
styleThe initial inline style.
stateThe current state name.
transitionTo(name, config?)Switches state.
machineThe core StateController. One object for the life of the component; machine.disposed is true after unmount.