Focused, tree-shakeable, TypeScript-first React hooks for application state, browser APIs, events, timing, and UI behavior.
Documentation Β·
Getting started Β·
Hook reference Β·
Contributing
Rooks supports React and React DOM 18 or 19. The package is ESM-only.
import { useCounter } from "rooks" ;
export function Counter ( ) {
const { value, increment, decrement, reset } = useCounter ( 0 ) ;
return (
< section >
< p > Count: { value } </ p >
< button type = "button" onClick = { decrement } >
Decrement
</ button >
< button type = "button" onClick = { increment } >
Increment
</ button >
< button type = "button" onClick = { reset } >
Reset
</ button >
</ section >
) ;
}
Continue with the three-step tutorial , or browse the hook index .
Rooks separates stable hooks, experimental hooks, and Temporal hooks so applications only opt into the compatibility and dependency surface they need.
Import path
Use it for
Stability
rooks
Stable hooks and explicitly exported utility types
Stable
rooks/experimental
Hooks whose API or behavior may change between minor releases
Experimental
rooks/temporal
Hooks built on the JavaScript Temporal API
Stable, optional polyfill required where Temporal is unavailable
import { useToggle } from "rooks" ;
Only types exported by an entrypoint are importable. Option and result shapes shown inline in a hook page are not necessarily public named exports.
import { useWebSocket } from "rooks/experimental" ;
Experimental hooks are isolated from the main entrypoint and can change in a minor release. Read the experimental hooks guide before using them in production.
Install the optional polyfill when your supported runtimes do not provide Temporal:
pnpm add @js-temporal/polyfill
import { useTemporalNow } from "rooks/temporal" ;
export function Clock ( ) {
const now = useTemporalNow ( { precision : "second" } ) ;
return < time > { now ?. toString ( ) ?? "Loading timeβ¦" } </ time > ;
}
Temporal hooks require BigInt support and have specific SSR and time-zone considerations. See the Temporal hooks guide .
Server rendering and browser APIs
Hooks that read browser globals handle server rendering in hook-specific ways. Components still need a client boundary in frameworks where hooks cannot run in server components, and permission-gated APIs need a fallback for unsupported or denied states.
Read SSR and browser APIs before using browser-only hooks in a server-rendered application.
The following counts and tables are generated from the package export barrels and the canonical MDX pages. Run pnpm docs:generate after adding or moving a public hook; CI verifies the zone with pnpm docs:generate --check.
147 canonical hook implementations are available across three entrypoints. Aliases are listed separately and do not inflate this count.
Entrypoint
Canonical hooks
rooks
118
rooks/experimental
25
rooks/temporal
4
Animation & Timing (10)
Hook
Description
Entrypoint
useAnimation
Deprecated progress animation hook; use useEasing for new code.
rooks
useEasing
Creates a controllable eased animation progress value.
rooks
useIntervalWhen
Runs the latest callback on an interval while a condition is true.
rooks
useLockBodyScroll
Sets document.body overflow to hidden while a condition is true.
rooks
usePrefersReducedMotion
Tracks the user's prefers-reduced-motion media setting.
rooks
useRaf
Runs the latest callback every animation frame while active.
rooks
useResizeObserverRef
Observes the size of the element attached to a callback ref.
rooks
useSpring
Animates a number toward a target with a basic damped spring simulation.
rooks
useTimeoutWhen
Runs the latest callback once after a delay while a condition remains true.
rooks
useTween
Animates an eased progress value from zero to one.
rooks
Browser APIs (16)
Hook
Description
Entrypoint
useBroadcastChannel
Enables cross-tab/window communication via the BroadcastChannel API.
rooks
useClipboard
Reads from and writes to the clipboard using the Clipboard API.
rooks
useFetch
Hook for fetching data from URLs with loading states, error handling, and automatic JSON parsing
rooks
useGeolocation
Tracks the user's geographic location using the Geolocation API.
rooks
useIdleDetectionApi
Detects when the user is idle using the IdleDetection API.
rooks
useMediaRecorder
Records audio/video streams using the MediaRecorder API.
rooks
useNavigatorLanguage
Returns the user's preferred language from the Navigator API.
rooks
useNetworkInformation
Exposes network connectivity and speed information from the Network Information API.
rooks
useNotification
Requests permission and sends desktop notifications via the Notifications API.
rooks
useOnline
Tracks the browser's navigator.onLine connectivity hint.
rooks
useOrientation
Returns the current screen orientation and listens for orientation changes.
rooks
useScreenDetailsApi
Provides details about the user's screens using the Screen Details API.
rooks
useShare
Triggers the native Web Share dialog to share content from the browser.
rooks
useSpeech
Converts text to speech using the Web Speech API.
rooks
useVibrate
Triggers device vibration patterns using the Vibration API.
rooks
useWebLocksApi
Coordinates asynchronous resource access using the Web Locks API.
rooks
Development & Debugging (2)
Hook
Description
Entrypoint
useRenderCount
Counts how many times the current hook instance has rendered.
rooks
useWhyDidYouUpdate
Logs tracked values whose identity changed between committed renders.
rooks
Event Handling (17)
Hook
Description
Entrypoint
useDocumentEventListener
Attaches a document event listener and removes it when the component unmounts.
rooks
useDocumentVisibilityState
Returns the document visibility state and updates when it changes.
rooks
useFocus
Provides focus and blur props for an element's own focus boundary.
rooks
useFocusWithin
Provides focus props that track entry to and exit from an element subtree.
rooks
useIsDroppingFiles
Reports whether files are being dragged over an element or the window.
rooks
useOnClickRef
Returns a ref that handles native click and touch-end events.
rooks
useOnHoverRef
Returns a ref that handles native mouse-enter and mouse-leave events.
rooks
useOnLongHover
Calls a callback after an element remains hovered for a duration.
rooks
useOnLongPress
Calls a callback after an element remains pressed for a duration.
rooks
useOnStartTyping
Calls a callback for allowed typing keys outside editable elements.
rooks
useOnWindowResize
Calls a callback for passive window resize events.
rooks
useOnWindowScroll
Calls a callback for passive window scroll events.
rooks
useOutsideClick
Calls a handler for click or touch-start events outside an object ref.
rooks
useOutsideClickRef
Returns a ref and calls a handler for click or touch-start events outside it.
rooks
usePageLeave
Calls a callback for unload, page-hide, and hidden-document signals.
rooks
useTextSelection
Returns the current text selection for the document or a target element.
rooks
useWindowEventListener
Attaches a window event listener and removes it when the component unmounts.
rooks
Experimental Hooks (25)
Hook
Description
Entrypoint
useAsyncDisposable
Manages async disposable resources using the TC39 Explicit Resource Management proposal.
rooks/experimental
useBeforeUnload
Prompt before the page unloads when a guard passes.
rooks/experimental
useBrowserCookieState
Persist React state in browser cookies with same-document synchronization.
rooks/experimental
useDisposable
Manages synchronous disposable resources using the TC39 Explicit Resource Management proposal.
rooks/experimental
useEventListener
Strongly typed event-listener primitive for browser EventTargets.
rooks/experimental
useIsClient
Tell whether the component has mounted on the client.
rooks/experimental
useKeyPress
Track whether one or more keyboard keys are currently pressed.
rooks/experimental
useLocationHash
Read the current location hash, including the leading #.
rooks/experimental
useLocationSearchParam
Read the first value for a specific search parameter.
rooks/experimental
useLocationSnapshot
Read the current browser location as a stable snapshot.
rooks/experimental
useMediaDevices
Enumerate and refresh available media input and output devices.
rooks/experimental
usePermission
Query and optionally watch browser permission state.
rooks/experimental
useRequest
Generic promise-request lifecycle hook with retries, polling, and mutation.
rooks/experimental
useResponsive
Track a named set of media queries and compute the current breakpoint.
rooks/experimental
useScript
Load and share external script state across multiple consumers.
rooks/experimental
useScroll
Track an element's scroll offsets and scrollable bounds.
rooks/experimental
useSize
Measure an element with ResizeObserver using a callback ref.
rooks/experimental
useSuspenseFavicon
Loads a favicon and suspends the component until the resource is ready.
rooks/experimental
useSuspenseIndexedDBState
Reads and writes IndexedDB state with Suspense support.
rooks/experimental
useSuspenseLocalStorageState
Reads and writes localStorage state with Suspense support.
rooks/experimental
useSuspenseNavigatorBattery
Reads battery status from the Battery API with Suspense support.
rooks/experimental
useSuspenseNavigatorUserAgentData
Reads User-Agent Client Hints with Suspense support.
rooks/experimental
useSuspenseSessionStorageState
Reads and writes sessionStorage state with Suspense support.
rooks/experimental
useVirtualList
Render a fixed-size virtual list with ready-to-use item styles.
rooks/experimental
useWebSocket
Manage a WebSocket connection with parsing, sending, and reconnection helpers.
rooks/experimental
Form & File Handling (3)
Hook
Description
Entrypoint
useCheckboxInputState
Returns controlled checkbox state, handlers, and input props.
rooks
useFileDropRef
Returns a ref that validates dropped files and reports accepted and rejected files.
rooks
useFormState
Manages named form values, validation, touched state, and submission.
rooks
Keyboard & Input (5)
Hook
Description
Entrypoint
useInput
Returns controlled input value and change props with optional validation.
rooks
useKey
Calls a callback when any configured keyboard identifier matches an event.
rooks
useKeyBindings
Maps independent keyboard identifiers to their callbacks.
rooks
useKeyRef
Returns a callback ref that handles matching keyboard events on an element.
rooks
useKeys
Calls a callback when every key in a configured combination is pressed.
rooks
Lifecycle & Effects (11)
Hook
Description
Entrypoint
useAsyncEffect
Runs asynchronous effect work with a current-generation guard and optional cleanup.
rooks
useDebouncedAsyncEffect
Starts only the latest asynchronous effect after a debounce window.
rooks
useDebouncedEffect
Delays an effect until its dependencies stop changing.
rooks
useDeepCompareEffect
Runs an effect when a dependency array changes by deep equality.
rooks
useDidMount
Runs a callback from an effect when a component mounts.
rooks
useDidUpdate
Runs a callback after updates while skipping the initial mount.
rooks
useDocumentTitle
Updates document.title and can restore its original value during cleanup.
rooks
useEffectOnceWhen
Runs the latest callback once when a condition first becomes true.
rooks
useIsomorphicEffect
Uses a layout effect in the browser and a passive effect during server rendering.
rooks
useLifecycleLogger
Logs a component's mount, update, and unmount lifecycle to the console.
rooks
useWillUnmount
Runs the initial callback as an effect cleanup when a component unmounts.
rooks
Mouse & Touch (3)
Hook
Description
Entrypoint
useMouse
Returns document-level mouse coordinates from the latest mousemove event.
rooks
useMouseMoveDelta
Returns movement and velocity between consecutive document mousemove events.
rooks
useMouseWheelDelta
Returns vertical wheel delta and velocity from document wheel events.
rooks
Performance & Optimization (5)
Hook
Description
Entrypoint
useDebounce
Returns a stable Lodash-style debounced wrapper around the latest callback.
rooks
useDebouncedValue
Returns a value that follows its input after a delay, plus an immediate setter.
rooks
useDebounceFn
Debounces a callback and reports whether its timeout window is active.
rooks
useThrottle
Executes a callback immediately at most once per timeout window.
rooks
useWebWorker
Creates and manages a classic Web Worker with message, status, and error state.
rooks
State Management (19)
Hook
Description
Entrypoint
useArrayState
Manages an array state with helper methods for push, pop, splice, sort, and more.
rooks
useCountdown
Counts the intervals remaining until a target Date and reports progress or completion.
rooks
useCounter
Manages a numeric counter with increment, decrement, and reset operations.
rooks
useGetIsMounted
Returns a function that reports whether the component is currently mounted.
rooks
useLocalstorageState
Persists React state in localStorage and synchronizes matching hook instances.
rooks
useMapState
Manages a record-like object as React state with keyed update and removal helpers.
rooks
useMultiSelectableList
Manages multiple-selection list state with toggle and select-all helpers.
rooks
useNativeMapState
Manages a native Map object in React state with reactive update helpers.
rooks
usePreviousDifferent
Returns the most recent previous value that was different from the current one.
rooks
usePreviousImmediate
Returns the previous value of a variable immediately after it changes.
rooks
usePromise
Tracks the status and result of a Promise (pending, resolved, or rejected).
rooks
useQueueState
Manages queue (FIFO) state with enqueue, dequeue, and peek operations.
rooks
useRafState
Updates React state on each requestAnimationFrame tick.
rooks
useSafeSetState
Calls setState only if the component is still mounted, preventing memory leaks.
rooks
useSelect
Manages a selection state from a list of options with helpers.
rooks
useSelectableList
Manages a single-selection list state with toggle and clear helpers.
rooks
useSessionstorageState
Persists React state in sessionStorage and synchronizes matching hook instances.
rooks
useSetState
Manages a Set data structure as React state with add, delete, and clear helpers.
rooks
useStackState
Manages stack (LIFO) state with push, pop, and peek operations.
rooks
State History & Time Travel (4)
Hook
Description
Entrypoint
useTimeTravelState
Manages state with undo, redo, and navigation across its complete history.
rooks
useToggle
Toggles a boolean or applies a custom reducer to another state type.
rooks
useUndoRedoState
Manages state with bounded undo and redo history.
rooks
useUndoState
Manages state with a bounded, one-directional undo history.
rooks
Temporal Hooks (4)
Hook
Description
Entrypoint
useTemporalAge
Calculates calendar age from a date and updates at each local day boundary.
rooks/temporal
useTemporalCountdown
Counts down to a Temporal instant and stops when the target is reached.
rooks/temporal
useTemporalElapsed
Measures elapsed time from an instant and updates on aligned boundaries.
rooks/temporal
useTemporalNow
Returns the current time as a Temporal value and updates on aligned time boundaries.
rooks/temporal
UI & Layout (14)
Hook
Description
Entrypoint
useAudio
Controls an audio element while exposing playback, loading, timing, volume, rate, loop, and error state.
rooks
useBoundingclientrect
Reads an element's DOMRect after mount and whenever the observed DOM subtree mutates.
rooks
useBoundingclientrectRef
Supplies a callback ref, its current DOMRect, and a manual measurement function.
rooks
useDimensionsRef
Measures an attached div after layout and optionally on window resize and scroll.
rooks
useFullscreen
Enters, exits, and tracks Fullscreen API state for the document or a target element.
rooks
useIntersectionObserverRef
Returns a callback ref that forwards IntersectionObserver notifications to the latest callback.
rooks
useInViewRef
Returns a callback ref and whether its element currently intersects an observer root.
rooks
useMeasure
Measures client, offset, and scroll dimensions with ResizeObserver and optional debouncing.
rooks
useMediaMatch
Subscribes to a CSS media query with a deterministic server-rendered fallback.
rooks
useMutationObserver
Observes mutations on the element in an existing object ref and cleans up automatically.
rooks
useMutationObserverRef
Returns a callback ref that observes DOM mutations on its current element.
rooks
usePictureInPictureApi
Detects, enters, exits, and tracks standard Picture-in-Picture state for a video element.
rooks
usePreferredColorScheme
Tracks the user's light, dark, or no-preference color-scheme media setting.
rooks
useVideo
Supplies a video ref with playback, timing, mute, volume, seeking, and fullscreen controls.
rooks
Utilities & Refs (7)
Hook
Description
Entrypoint
useEventListenerRef
Returns a callback ref that manages an event listener on its current HTML element.
rooks
useForkRef
Sends one ref value to two mutable or callback refs.
rooks
useFreshCallback
Returns a stable function that delegates to the latest callback after effects run.
rooks
useFreshRef
Keeps the latest committed value in a stable mutable ref.
rooks
useFreshTick
Returns a function that invokes the latest void callback after effects run.
rooks
useMergeRefs
Sends one ref value to any number of mutable or callback refs.
rooks
useRefElement
Exposes a callback ref together with the element currently attached to it.
rooks
Window & Viewport (2)
Hook
Description
Entrypoint
useWindowScrollPosition
Returns reactive horizontal and vertical window scroll coordinates.
rooks
useWindowSize
Returns reactive inner and outer browser window dimensions.
rooks
Every hook page is hand-authored MDX under apps/website/content/docs. Import paths, aliases, status, signatures, and README catalog data are validated against the package barrels.
Community
Rooks is available under the MIT License .
View the current contributor graph .
Thanks to everyone who has contributed to Rooks. The historical acknowledgements below use the All Contributors emoji key ; the contributor graph above is the current record.
View historical acknowledgements