— Hooks · @vitus-labs/hooks
Small hooks, careful edges.
36 hooks for the parts of a UI React leaves to you: media queries, focus traps, scroll locks, storage, observers and timers. The ones that read browser state are built on useSyncExternalStore, so server HTML and hydration agree. The ones that take a callback always call the latest one.
npm i @vitus-labs/hooks @vitus-labs/core- hooks, one import
- 36
- also exported on React Native
- 21
- resize listener for every useBreakpoint
- 1
— Why hooks
The edge cases, already handled.
Hydration-safe by construction
useMediaQuery, useLocalStorage, useBreakpoint, usePageVisibility and useOnlineStatus are built on useSyncExternalStore. The server and the hydrating client render the same fallback, then React re-renders with the real value. Client-only renders get the real value on the first pass.
No stale closures
Hooks that take a handler keep the latest one in a ref: useDebouncedCallback, useThrottledCallback, useInterval, useTimeout, useKeyboard, useClickOutside, useEventListener. The listener stays attached while the handler stays current.
Shared, not duplicated
Every useBreakpoint shares one rAF-throttled resize listener. useLocalStorage keeps same-key instances in sync within the tab and across tabs. useScrollLock counts its locks, so stacked modals restore the original overflow only when the last one closes.
Accessibility, done properly
useFocusTrap moves focus in, cycles Tab and Shift+Tab, and restores focus when it's disabled, as the WAI-ARIA dialog pattern asks. It caches the focusable elements and refreshes them only when the DOM inside changes.
— Before / after
Same media query. No mismatch.
A layout that switches at 1000 px. The hand-rolled hook is the one most codebases have; it works until the page is server-rendered.
import { useEffect, useState } from 'react'
export function useMediaQuery(query: string) {
const [matches, setMatches] = useState(
() => typeof window !== 'undefined' && window.matchMedia(query).matches,
)
useEffect(() => {
const mql = window.matchMedia(query)
const onChange = () => setMatches(mql.matches)
mql.addEventListener('change', onChange)
return () => mql.removeEventListener('change', onChange)
}, [query])
return matches
}
// const wide = useMediaQuery('(min-width: 1000px)')Reading window in the initializer renders false on the server and true on a wide client's first pass: a hydration mismatch.
import { useMediaQuery } from '@vitus-labs/hooks'
export function Layout({ nav, children }) {
const wide = useMediaQuery('(min-width: 1000px)')
return (
<div className={wide ? 'two-column' : 'stacked'}>
{wide && <aside>{nav}</aside>}
<main>{children}</main>
</div>
)
}Server and hydration render false, then React re-renders with the live value. One MediaQueryList per query, read as a property on every snapshot.
— Live, not a screenshot
Ten hooks, live.
Every value on the right is what the hook returned on this render. Type, click, resize the box, scroll the page or switch your OS theme. The click count is in localStorage, so it survives a reload.
import {
useColorScheme, useCopyToClipboard, useDebouncedValue,
useElementSize, useLocalStorage, useMediaQuery, useOnlineStatus,
usePageVisibility, useReducedMotion, useWindowScroll,
} from '@vitus-labs/hooks'
const scheme = useColorScheme()
const reduced = useReducedMotion()
const wide = useMediaQuery('(min-width: 1000px)')
const visible = usePageVisibility()
const online = useOnlineStatus()
const { y } = useWindowScroll()
const debounced = useDebouncedValue(query, 400)
const [clicks, setClicks, remove] = useLocalStorage('vl-demo-clicks', 0)
const [boxRef, size] = useElementSize()
const [copied, copy] = useCopyToClipboard()useColorScheme()'light' useReducedMotion()false useMediaQuery('(min-width: 1000px)')false usePageVisibility()true useOnlineStatus()true useWindowScroll().y0 useDebouncedValue(query, 400)'' useLocalStorage('vl-demo-clicks', 0)0 useElementSize(){ width: 0, height: 0 } useCopyToClipboard()false
— Features
Picked for what UIs need.
- useControllableState
one API for controlled and uncontrolled components;
onChangefires in both modes - useLocalStorage
JSON state synced across instances and tabs, with
remove(); private mode and full quota fall back to memory - useFocusTrap
Tab cycling, focus in on enable and back on disable,
aria-disabledfiltered, contenteditable and media controls included - useScrollLock
reference-counted
overflow: hiddenonbody, so concurrent locks don't clobber each other - useClickOutside
one
pointerdownper tap, andcomposedPath()so shadow DOM and removed targets are handled - useElementSize · useIntersection
callback refs over
ResizeObserver(border box) andIntersectionObserver - useDebouncedCallback
stable debounced function with
.cancel()and.flush();useThrottledCallbackhas.cancel() - useInterval · useTimeout
declarative timers;
nullpauses,useTimeoutreturnsresetandclear - useMediaQuery · useBreakpoint
live query matches, and the active breakpoint name from your theme's
breakpoints - useThemeValue · useRootSize · useSpacing
dot-path theme reads, px↔rem converters and a
spacing(n)scale from the theme'srootSize - useCopyToClipboard
async Clipboard API with an
execCommandfallback, and acopiedflag that resets after 2 s - useMergedRef
merges callback and object refs into one, and honors React 19 ref cleanup functions
- useColorScheme · useReducedMotion
OS preferences, through media queries on the web and
Appearance/AccessibilityInfoon native - useIsClient · useIsomorphicLayoutEffect
the small SSR helpers:
falseuntil mounted, and a layout effect that doesn't warn on the server
— API
36 hooks, four shelves.
Every name links to its reference in the docs.
— Honest limits
When to reach for something else.
Where it isn't the right fit, and what to reach for instead.
You don't use the rest of the ui-system
The package peers on
@vitus-labs/core: the theme hooks read core's context, and the throttled ones use core'sthrottle. If you only want generic hooks in an app without the ui-system, a standalone collection such as usehooks-ts avoids that peer.Layout that must be right in the first paint
Hydration-safe means the server value renders first:
false, the initial value, or the smallest breakpoint, then the real one. For layout that can't flash, use a CSS media query and keep the hook for behavior.Theme hooks without a Provider
useBreakpoint,useThemeValue,useRootSizeanduseSpacingread core'sProvider. Without one,useBreakpointreturnsundefinedanduseRootSizeassumes 16. Mount the Provider, or useuseMediaQuerywith literal queries.Hidden elements inside a focus trap
useFocusTrapdoesn't check visibility, because reading layout on every refresh is costly. Focusable elements inside adisplay: nonesubtree stay in the Tab cycle. Remove them from the DOM or mark themdisabled.DOM hooks on React Native
15 hooks aren't exported on native, among them
useHover,useFocus,useFocusTrapand the observers, anduseKeyboardis a no-op there. UsePressable'sonHoverIn/onHoverOutandTextInput's focus events directly.
— Recipes
Copy, paste, ship.
An accessible modal in four hooks
Focus moves in and comes back, the page stops scrolling, Escape and an outside click both close it.
import { useRef } from 'react'
import {
useClickOutside,
useFocusTrap,
useKeyboard,
useScrollLock,
} from '@vitus-labs/hooks'
export function Modal({ open, onClose, children }) {
const ref = useRef<HTMLDivElement>(null)
useFocusTrap(ref, open)
useScrollLock(open)
useKeyboard('Escape', () => open && onClose())
useClickOutside(ref, () => open && onClose())
if (!open) return null
return (
<div role="dialog" aria-modal="true" ref={ref}>
{children}
</div>
)
}Controlled or uncontrolled, one component
Pass open to control it, or defaultOpen and let it manage itself. onOpenChange fires either way.
import { useControllableState } from '@vitus-labs/hooks'
export function Disclosure({ open, defaultOpen = false, onOpenChange, title, children }) {
const [isOpen, setOpen] = useControllableState({
value: open,
defaultValue: defaultOpen,
onChange: onOpenChange,
})
return (
<>
<button aria-expanded={isOpen} onClick={() => setOpen((o) => !o)}>
{title}
</button>
{isOpen && children}
</>
)
}Search that waits for a pause
The input stays instant; the request only follows the debounced value. Recent queries persist across reloads and tabs.
import { useEffect, useState } from 'react'
import { useDebouncedValue, useLocalStorage } from '@vitus-labs/hooks'
export function Search({ onSearch }) {
const [query, setQuery] = useState('')
const debounced = useDebouncedValue(query, 300)
const [recent, setRecent] = useLocalStorage<string[]>('recent-searches', [])
useEffect(() => {
if (!debounced) return
onSearch(debounced)
setRecent((r) => [debounced, ...r.filter((q) => q !== debounced)].slice(0, 5))
}, [debounced])
return <input value={query} onChange={(e) => setQuery(e.target.value)} />
}— FAQ
Questions, answered.
Do I need a CSS engine or init() to use them?
No. You need @vitus-labs/core installed because the package imports its context and throttle, but no connector and no init(). The theme hooks only need core's Provider mounted.
Are they safe with server rendering?
Yes. Browser reads happen in effects or through useSyncExternalStore with a server snapshot, so the server and the hydrating client render the same thing. useWindowScroll returns { x: 0, y: 0 } until mounted; useIsClient is false until then.
Which hooks work on React Native?
21 of them: the state, timing and theme hooks, plus native versions of useColorScheme (Appearance), useReducedMotion (AccessibilityInfo), useWindowResize and useBreakpoint. The DOM and pointer hooks are web-only.
Why does useMergedRef care about React 19?
In React 19 a callback ref may return a cleanup function, and React then calls that instead of calling the ref with null. useMergedRef collects each ref's cleanup and runs them all on detach, so merged refs keep that behavior.
— @vitus-labs/hooks
Import the hook. Skip the edge cases.
npm i @vitus-labs/hooks @vitus-labs/coreSources · 43 claims, each traced to v2.9.1 code or docs
- Hook count 36 is facts.hooks, counted from the published type declarationssite:src/lib/facts.ts
- All hooks exported from one entry pointui-system:packages/hooks/src/index.ts
- useMediaQuery built on useSyncExternalStore; server/hydration render false, client-only renders get the real value firstui-system:packages/hooks/src/useMediaQuery.ts
- useMediaQuery keeps one MediaQueryList per query; snapshot is a property readui-system:packages/hooks/src/useMediaQuery.ts
- useLocalStorage built on useSyncExternalStore; server/hydration render initialValueui-system:packages/hooks/src/useLocalStorage.ts
- useLocalStorage instances with the same key stay in sync within the tab and across tabsui-system:packages/hooks/src/useLocalStorage.ts
- useLocalStorage private mode / quota errors keep the value in memoryui-system:packages/hooks/src/useLocalStorage.ts
- useLocalStorage returns [value, setValue, remove]ui-system:packages/hooks/src/useLocalStorage.ts
- useBreakpoint: one shared rAF-throttled resize listener for every instance; useSyncExternalStoreui-system:packages/hooks/src/useBreakpoint.ts
- useBreakpoint server/hydration snapshot is the smallest breakpointui-system:packages/hooks/src/useBreakpoint.ts
- useBreakpoint returns undefined without Provider/breakpointsui-system:packages/hooks/src/useBreakpoint.ts
- usePageVisibility and useOnlineStatus use useSyncExternalStoreui-system:packages/hooks/src/usePageVisibility.ts
- useOnlineStatus uses useSyncExternalStoreui-system:packages/hooks/src/useOnlineStatus.ts
- useDebouncedCallback: latest callback, .cancel() and .flush()ui-system:packages/hooks/src/useDebouncedCallback.ts
- useThrottledCallback: latest callback, uses core's throttle, cancel on unmountui-system:packages/hooks/src/useThrottledCallback.ts
- useInterval: null pauses; latest callbackui-system:packages/hooks/src/useInterval.ts
- useTimeout returns reset and clearui-system:packages/hooks/src/useTimeout.ts
- useKeyboard calls the latest handlerui-system:packages/hooks/src/useKeyboard.ts
- useClickOutside keeps the latest handler; pointerdown once per tap; composedPath for removed targets / shadow DOMui-system:packages/hooks/src/useClickOutside.ts
- useEventListener handler captured via ref, listener stays stableui-system:packages/hooks/src/useEventListener.ts
- useScrollLock reference-counts concurrent locks; overflow hidden on bodyui-system:packages/hooks/src/useScrollLock.ts
- useFocusTrap: focus in on enable, restore on disable (WAI-ARIA dialog), Tab/Shift+Tab cycleui-system:packages/hooks/src/useFocusTrap.ts
- useFocusTrap caches focusables, refreshes on DOM mutationsui-system:packages/hooks/src/useFocusTrap.ts
- useFocusTrap filters aria-disabled, includes contenteditable and media controlsui-system:packages/hooks/src/useFocusTrap.ts
- useFocusTrap leaves visibility (display:none) to the consumerui-system:packages/hooks/src/useFocusTrap.ts
- useControllableState: onChange fires in both modesui-system:packages/hooks/src/useControllableState.ts
- useElementSize measures the border box with ResizeObserverui-system:packages/hooks/src/useElementSize.ts
- useIntersection returns [ref, entry] over IntersectionObserverui-system:packages/hooks/src/useIntersection.ts
- useThemeValue deep-reads a dot path from the themeui-system:packages/hooks/src/useThemeValue.ts
- useRootSize defaults to 16 without a Providerui-system:packages/hooks/src/useRootSize.ts
- useSpacing: spacing(n) from rootSize / 2ui-system:packages/hooks/src/useSpacing.ts
- Theme hooks read @vitus-labs/core's contextui-system:packages/hooks/src/useThemeValue.ts
- useCopyToClipboard: Clipboard API, execCommand fallback, copied resets after 2000 msui-system:packages/hooks/src/useCopyToClipboard.ts
- useMergedRef supports React 19 ref cleanupsui-system:packages/hooks/src/useMergedRef.ts
- useColorScheme on native uses Appearanceui-system:packages/hooks/src/useColorScheme.native.ts
- useReducedMotion on native uses AccessibilityInfoui-system:packages/hooks/src/useReducedMotion.native.ts
- Native index exports 21 hooks; useHover/useFocus intentionally not exportedui-system:packages/hooks/src/index.native.ts
- useKeyboard is a no-op on React Nativeui-system:packages/hooks/src/useKeyboard.native.ts
- useWindowScroll returns {0,0} on the server and until mountui-system:packages/hooks/src/useWindowScroll.ts
- useIsomorphicLayoutEffect: useLayoutEffect on the client, useEffect on the server; avoids the SSR warningui-system:packages/hooks/src/useIsomorphicLayoutEffect.ts
- useIsClient false on server and first client renderui-system:packages/hooks/src/useIsClient.ts
- Peer dependencies: @vitus-labs/core and react >= 19 (react-native optional)npm:@vitus-labs/hooks/package.json
- Published bundle imports @vitus-labs/corenpm:@vitus-labs/hooks/lib/index.js