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,initialValueandclockare read on the first render only, like the initial value ofuseState. To start from different props, remount with akey. - Rendering.
stateis the machine's state and re-renders on transitions, also on transitions made directly onmachine. Frames never render. - Stable
transitionTo. It keeps its identity across renders and returns the promise of the run ('ended','interrupted', ...). An unknown state throws aRangeErrorand 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.
styleis built frominitialValueand rendered into the HTML. Nothing subscribes.
API Reference
| Name | Type | Description |
|---|---|---|
config | StateProps & { resolver? } | initial, initialValue, states, optional clock, optional style resolver. See createStates. |
Returns:
| Member | Description |
|---|---|
ref | Element ref. |
style | The initial inline style. |
state | The current state name. |
transitionTo(name, config?) | Switches state. |
machine | The core StateController. One object for the life of the component; machine.disposed is true after unmount. |
Related Components
createStates- The core function this hook is built on.useAniRef- For your own timeline.