$ show szhsin/react-transition-state
This repository is a zero-dependency React library for managing CSS transitions via a controlled state machine. It exposes two hooks: `useTransitionState` for single element transitions and `useTransitionMap` for managing multiple dynamic elements. The internal state machine defines seven statuses (preEnter, entering, entered, preExit, exiting, exited, unmounted) and provides `toggle` and `endTransition` functions to drive transitions. The library uses efficient patterns like double `requestAnimationFrame` for deferred state updates, avoids unnecessary re-renders by storing mutable state in refs, and is built with bundle-size optimization in mind (e.g., single-character internal property names). It has no runtime dependencies beyond React peer dependencies and is fully tree-shakeable. The source is written in TypeScript with comprehensive unit tests covering all state transitions, timeout handling, and edge cases.
The LLM identified 2 files worth highlighting for reuse:
This module defines the core state machine constants, types, and utility functions (`getState`, `getEndStatus`, `nextTick`). It uses numeric state codes and single-character property names to minimize bundle size. The `nextTick` function employs a double `requestAnimationFrame` pattern to ensure a callback runs after the browser has rendered the next frame, which is critical for syncing state transitions with CSS animations. This module is self-contained (only imports from `types.ts`) and could be extracted and reused as a lightweight state machine foundation for any transition-related library.
This file implements the primary `useTransitionState` hook. It manages a state machine using React `useState` for the current state and a `useState`-initialized ref object to hold mutable state and timer IDs without causing re-renders. The `toggle` function orchestrates transitions through the state machine, conditionally enabling `preEnter`/`preExit` phases and handling timeout-based auto-transitions. The hook demonstrates a robust pattern for building controlled, state-driven animations with minimal overhead and could serve as a template for similar custom hooks.