UNPKG

react-css-transition-hook

Version:

Minimal, zero-dependency React hook to CSS class name based transitions.

39 lines (38 loc) 1.26 kB
// src/useTransition.ts import { useCallback, useEffect, useState } from "react"; function useTransition(desiredState, opts) { const [currentState, setCurrentState] = useState(Boolean(desiredState && opts.disableInitialEnterTransition)); const [transition, setTransition] = useState(() => desiredState ? "entered" : null); useEffect(() => { if (!currentState && desiredState) { setCurrentState(true); setTransition("entering"); runAfterFramePaint(() => setTransition("entered")); } else if (currentState && !desiredState) { setTransition("exiting"); runAfterFramePaint(() => setTransition("exited")); } }, [currentState, desiredState]); const onTransitionEnd = useCallback(() => { if (!desiredState) { setCurrentState(false); setTransition(null); } }, [desiredState]); return [ currentState, { className: transition ? opts[transition] ?? "" : "", onTransitionEnd }, transition ]; } function runAfterFramePaint(callback) { requestAnimationFrame(() => { const messageChannel = new MessageChannel(); messageChannel.port1.onmessage = callback; messageChannel.port2.postMessage(void 0); }); } export { useTransition }; //# sourceMappingURL=useTransition.js.map