Skip to Content
vitus·labs
Kinetic

Kinetic

CSS-first animation primitives for React — a chainable factory with four modes (transition, collapse, stagger, group).

@vitus-labs/kinetic delegates animation interpolation to the browser's CSS transition engine — transform and opacity run on the GPU compositor thread — and only handles orchestration: mount/unmount lifecycle, stagger timing, height measurement, and key-based list reconciliation. The result is GPU-composited 60/120 FPS animations at ~4 KB min+gzipped.

The library exposes a single chainable factory, kinetic(tag), that returns a renderable React component with chain methods attached. There are no <Transition> / <Collapse> / <Stagger> components to import — those are internal renderers that the factory dispatches to based on which chain method you called.

Installation

npm install @vitus-labs/kinetic

Peer dependencies: react >= 19, @vitus-labs/hooks (and optionally react-native >= 0.76 — a native build ships under the react-native export condition).

What's new in 2.9 — a round of correctness fixes:

  • Once a phase settles, kinetic restores the inline styles the phase overwrote. Final transform / filter / clip-path values no longer linger after entered (they broke position: fixed descendants and clipped overflow), and the element's own inline transform / transition survive. The enterToStyle values are therefore not left inline — put the resting state in the element's own style or classes.
  • Reversing a transition mid-flight continues from the current state instead of flashing the opposite phase's start state.
  • Turning reduced motion on mid-transition completes the phase instead of hanging.
  • Collapse: content is wrapped in a display: flow-root block so child margins are measured (no jump at the end), and reversing mid-animation starts from the current height.
  • Phases also complete on transitioncancel, or when getAnimations() reports nothing running (e.g. a 0px → 0px collapse or a display: none ancestor).
  • appear with SSR renders the element in its enter start state, and the hydration render matches it.
  • Stagger: onAfterLeave still fires when a child is added during leave, onAfterEnter fires once (for the last child), and transition-delay is no longer copied into children's style.

Try It Live

The first block is a transition-mode component with the fadeUp preset; its lifecycle callbacks drive the stage label. The second uses .collapse().

Quick Start

Create animated components at module level by chaining onto kinetic(tag):

import { kinetic, fade, slideUp } from '@vitus-labs/kinetic'

const FadeDiv = kinetic('div').preset(fade)
const SlideSection = kinetic('section').preset(slideUp)

function App() {
  const [show, setShow] = useState(true)

  return (
    <>
      <button onClick={() => setShow(!show)}>Toggle</button>
      <FadeDiv show={show}>Hello, world!</FadeDiv>
    </>
  )
}

FadeDiv is a real React component. The tag argument flows through the type system, so <FadeDiv> accepts all the HTML attributes of a <div> plus kinetic's animation props (show, appear, unmount, lifecycle callbacks).

Core Concepts

Two Animation Approaches

Kinetic supports two ways to define animations. You can mix and match both on the same component.

Style-based — inline CSSProperties objects, zero external CSS needed:

const Panel = kinetic('aside')
  .enter({ opacity: 0, transform: 'translateX(-100%)' })
  .enterTo({ opacity: 1, transform: 'translateX(0)' })
  .enterTransition('all 300ms ease-out')
  .leave({ opacity: 1, transform: 'translateX(0)' })
  .leaveTo({ opacity: 0, transform: 'translateX(-100%)' })
  .leaveTransition('all 200ms ease-in')

Class-based — CSS class names (works with Tailwind, CSS modules, or any class-based approach):

const TailwindFade = kinetic('div')
  .enterClass({
    active: 'transition-opacity duration-300',
    from: 'opacity-0',
    to: 'opacity-100',
  })
  .leaveClass({
    active: 'transition-opacity duration-200',
    from: 'opacity-100',
    to: 'opacity-0',
  })

Lifecycle Stages

Every transition moves through four stages:

hidden ─── show=true ──→ entering ──→ entered
                                        │
                         ┌── show=false ─┘
                         ▼
                       leaving ──→ hidden (unmount)
StageDescription
hiddenElement is unmounted (or display: none if unmount={false})
enteringEnter animation is playing — start styles applied, then end styles on next frame
enteredEnter animation complete, element is fully visible
leavingLeave animation is playing, then transitions back to hidden

How a Transition Runs Internally

  1. Enter: On mount (or when show flips to true), kinetic applies the enter (active) and enterFrom classes, enterStyle, and enterTransition. After a double requestAnimationFrame (so the start state paints) it swaps enterFrom for enterTo and applies enterToStyle. The browser's CSS transition engine animates between the two states.
  2. Detection: Kinetic listens for transitionend, transitioncancel and animationend on the element and ignores bubbled events from children (event.target === element). When several properties transition it waits for the longest one. If durations are explicitly zero, or getAnimations() reports nothing running, the phase completes after a few frames. A safety timeout (default 5000 ms) completes the transition if no event ever fires — e.g. when a custom component doesn't attach the ref (a dev warning is logged).
  3. Leave: Removes the enter classes, applies leave / leaveFrom and leaveStyle, then on the next frames swaps to leaveTo / leaveToStyle. After completion the element unmounts (or hides if unmount={false}). If show flips while a phase is still running, the new phase continues from the current state (no flash of the start state).
  4. Settle: When a phase finishes, the inline style values it touched are restored to what they were before the phase, and the enterFrom / leaveFrom (and, after entering, the active enter) classes are removed; the enterTo class stays on. For style-based animations the visible resting state is therefore whatever the element's own styles/classes give it.
  5. Unmount behaviour: Default is unmount={true} — element is removed from the DOM. Set unmount={false} to keep it with display: none (useful for preserving scroll position or form state).

The Four Modes

kinetic(tag) returns a transition-mode component by default. Switch modes by chaining one of the mode methods.

ModeHow to enter itWhat it does
transitiondefault (no method)Single element enter/leave with CSS transitions
collapse.collapse(opts?)Height animation — measures scrollHeight automatically
stagger.stagger(opts?)Sequential enter/exit of child elements with configurable delay
group.group()Key-based list reconciliation — adding a child triggers enter, removing triggers leave

Transition (default)

import { kinetic, fade } from '@vitus-labs/kinetic'

const FadeDiv = kinetic('div').preset(fade)

<FadeDiv show={isOpen}>Modal content</FadeDiv>

Props: show, appear?, unmount?, timeout?, lifecycle callbacks, plus all attributes of the chosen tag.

Collapse

Height-based expand/collapse. The chosen tag becomes the outer wrapper; the children are rendered inside an inner <div style="display: flow-root"> whose scrollHeight is measured (the block formatting context makes child margins count). Kinetic animates the wrapper's height from 0 to that value on enter and back to 0 on leave, with overflow: hidden during the animation; once entered, the height is set to auto. While collapsed the wrapper stays mounted at height: 0 and the children are unmounted. Reversing mid-animation starts from the current height.

const Accordion = kinetic('div').collapse()
const FancyAccordion = kinetic('section').collapse({
  transition: 'height 400ms cubic-bezier(0.4, 0, 0.2, 1)',
})

<Accordion show={isExpanded}>
  <p>Expandable content of any height.</p>
  <p>Height is measured automatically.</p>
</Accordion>

Props: show, appear?, timeout?, transition?, lifecycle callbacks.

Stagger

Sequential enter / exit for child elements. Each child's animation starts interval ms after the previous one. The component itself follows the chained preset / inline config — children inherit the same animation but with cascading delays.

import { kinetic, slideUp } from '@vitus-labs/kinetic'

const StaggerList = kinetic('ul').preset(slideUp).stagger({ interval: 75 })

<StaggerList show={isVisible}>
  <li key="1">Item 1</li>
  <li key="2">Item 2</li>
  <li key="3">Item 3</li>
</StaggerList>

Props: show, appear?, interval? (default 50 ms), reverseLeave? (reverses stagger order on leave), timeout?, lifecycle callbacks. Each child gets --stagger-index and --stagger-interval CSS custom properties on its style. onEnter / onLeave fire per child, onAfterEnter fires once (for the last child), and onAfterLeave fires once every child that started leaving has finished. Each child's safety timeout is extended by its delay.

Group

Key-based enter / exit for dynamic lists. There is no show prop — adding a child to the array triggers its enter animation, removing one triggers leave + unmount. Each child must have a stable key.

import { kinetic, fade } from '@vitus-labs/kinetic'

const AnimatedList = kinetic('ul').preset(fade).group()

<AnimatedList>
  {items.map(item => <li key={item.id}>{item.text}</li>)}
</AnimatedList>

Props: appear?, timeout?, lifecycle callbacks. The appear flag controls whether the initial set of children animates in on mount (default false); children added later always animate in. A leaving child keeps its position in the list until its exit completes, and re-adding its key mid-leave cancels the exit. onAfterLeave fires for each child that finishes leaving. Children without a key trigger a development warning.

Inline Configuration

You can build animations without a preset by using the style or class chain methods directly:

const SlidePanel = kinetic('aside')
  .enter({ opacity: 0, transform: 'translateX(-100%)' })
  .enterTo({ opacity: 1, transform: 'translateX(0)' })
  .enterTransition('all 300ms ease-out')
  .leave({ opacity: 1, transform: 'translateX(0)' })
  .leaveTo({ opacity: 0, transform: 'translateX(-100%)' })
  .leaveTransition('all 200ms ease-in')

Behaviour Defaults via .config()

Mode-agnostic and mode-specific defaults are configured via .config(opts). The accepted shape narrows based on the mode you're in.

// Transition mode: appear, unmount, timeout
const Tooltip = kinetic('div')
  .preset(fade)
  .config({ appear: true, unmount: false, timeout: 8000 })

// Collapse mode: appear, timeout, transition
const Accordion = kinetic('div').collapse().config({
  transition: 'height 250ms ease-in-out',
})

// Stagger mode: appear, timeout, interval, reverseLeave
// (.stagger() itself only accepts { interval, reverseLeave })
const Menu = kinetic('ul').preset(slideUp).stagger().config({
  interval: 60,
  reverseLeave: true,
})

Defaults can also be overridden per render via the same-named props (<FadeDiv timeout={10000} />).

Lifecycle Callbacks

Attach callbacks via .on() (component-level default) or as props (per-render override):

const Card = kinetic('div').preset(fade).on({
  onEnter: () => console.log('entering'),
  onAfterEnter: () => console.log('entered'),
  onLeave: () => console.log('leaving'),
  onAfterLeave: () => console.log('left'),
})

<Card
  show={isOpen}
  onAfterEnter={() => trackImpression()}  // overrides on() for this instance
>
  Content
</Card>
CallbackWhen it fires
onEnterEnter phase begins (start styles applied)
onAfterEnterEnter animation completes
onLeaveLeave phase begins
onAfterLeaveLeave animation completes (just before unmount)

In prefers-reduced-motion: reduce mode, the visible animation is skipped but callbacks still fire (onEnter then onAfterEnter immediately, likewise for leave) — your tracking and side-effects keep working.

Type Inference

The tag argument flows through the chain so the resulting component types its HTML attributes correctly:

const FadeDiv = kinetic('div').preset(fade)
<FadeDiv show className="x" onClick={fn} />     // div attributes ✓

const FadeInput = kinetic('input').preset(fade)
<FadeInput show type="text" value="x" />        // input attributes ✓

const FadeCustom = kinetic(MyComponent).preset(fade)
<FadeCustom show customProp="x" />              // MyComponent props ✓

When you switch modes the prop shape narrows automatically — e.g. .group() removes the show prop, .stagger() requires children (one element or an array of elements).

Accessibility

Kinetic detects prefers-reduced-motion: reduce via the useReducedMotion hook from @vitus-labs/hooks. When reduced motion is requested the visual animation is skipped instantly, but lifecycle callbacks still fire so analytics, focus management, and other side-effects remain consistent. If the preference flips on while a transition is running, the current phase completes immediately (2.9 — previously it could hang until the timeout). No configuration needed.

Because useReducedMotion is hydration-safe as of 2.9, it reports false during SSR and hydration and updates right after.

Composition with Rocketstyle

Kinetic and rocketstyle compose naturally — pass the rocketstyle component as the tag:

import rocketstyle from '@vitus-labs/rocketstyle'
import { kinetic, fade } from '@vitus-labs/kinetic'

const Button = rocketstyle()({ component: 'button', name: 'Button' })
  .theme({ primaryColor: 'blue' })

const AnimatedButton = kinetic(Button).preset(fade)

<AnimatedButton show={isVisible} primary size="large">
  Click me
</AnimatedButton>

AnimatedButton accepts both rocketstyle dimension props (primary, size) and kinetic animation props (show).

Built-in Presets

Six presets ship in the core package:

import {
  fade,
  scaleIn,
  slideUp,
  slideDown,
  slideLeft,
  slideRight,
} from '@vitus-labs/kinetic'

const Panel = kinetic('aside').preset(slideRight)

For 122 presets plus factory generators (createFade, createSlide, createScale, createRotate, createBlur) and composition helpers (compose, withDuration, withEasing, withDelay, reverse), install @vitus-labs/kinetic-presets. Note that some preset names exist in both packages with slightly different values (e.g. core scaleIn starts at scale(0.95), the kinetic-presets scaleIn at scale(0.9)).

Hooks

Two low-level hooks are exported for cases the chain factory doesn't cover:

import { useTransitionState, useAnimationEnd } from '@vitus-labs/kinetic'
  • useTransitionState — the state machine that powers transition mode. Takes { show, appear? } and returns { stage, ref, shouldMount, appearing, complete }. Drive enter/leave manually when you need behaviour the chain factory doesn't expose (e.g. coordinating animations with imperative APIs).
  • useAnimationEnd — takes { ref, onEnd, active, timeout?, phase? } and wraps transitionend / transitioncancel / animationend detection with a safety timeout fallback. Filters bubbled events from children automatically.

See the API Reference for full hook signatures.

Exports

import {
  // Factory + presets
  kinetic,
  presets,
  fade,
  scaleIn,
  slideUp,
  slideDown,
  slideLeft,
  slideRight,
  // Hooks
  useTransitionState,
  useAnimationEnd,
} from '@vitus-labs/kinetic'

import type {
  // Component types
  KineticComponent,
  // Preset types
  Preset,
  // Animation prop shapes
  ClassTransitionProps,
  StyleTransitionProps,
  TransitionCallbacks,
  TransitionStage,
  TransitionStateResult,
  // Hook return types
  UseTransitionState,
  UseAnimationEnd,
} from '@vitus-labs/kinetic'

There is no Transition, Collapse, Stagger, or TransitionGroup component to import. Those are internal renderers — the public surface is kinetic(tag).<chain> and the hooks above.

Edit on GitHub

Last updated on

On this page