— 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.

@vitus-labs/hooksv2.9.1 · MIT
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.

01

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.

02

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.

03

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.

04

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.

beforeHand-rolled
useMediaQuery.ts
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.

after@vitus-labs/hooks
Layout.tsx
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.

stored in localStorage · survives reload
drag the corner · measured by ResizeObserver
0 × 0
Panel.tsx
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()
return valueslive
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; onChange fires 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-disabled filtered, contenteditable and media controls included

  • useScrollLock

    reference-counted overflow: hidden on body, so concurrent locks don't clobber each other

  • useClickOutside

    one pointerdown per tap, and composedPath() so shadow DOM and removed targets are handled

  • useElementSize · useIntersection

    callback refs over ResizeObserver (border box) and IntersectionObserver

  • useDebouncedCallback

    stable debounced function with .cancel() and .flush(); useThrottledCallback has .cancel()

  • useInterval · useTimeout

    declarative timers; null pauses, useTimeout returns reset and clear

  • 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's rootSize

  • useCopyToClipboard

    async Clipboard API with an execCommand fallback, and a copied flag 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 / AccessibilityInfo on native

  • useIsClient · useIsomorphicLayoutEffect

    the small SSR helpers: false until 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's throttle. 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, useRootSize and useSpacing read core's Provider. Without one, useBreakpoint returns undefined and useRootSize assumes 16. Mount the Provider, or use useMediaQuery with literal queries.

  • Hidden elements inside a focus trap

    useFocusTrap doesn't check visibility, because reading layout on every refresh is costly. Focusable elements inside a display: none subtree stay in the Tab cycle. Remove them from the DOM or mark them disabled.

  • DOM hooks on React Native

    15 hooks aren't exported on native, among them useHover, useFocus, useFocusTrap and the observers, and useKeyboard is a no-op there. Use Pressable's onHoverIn / onHoverOut and TextInput's focus events directly.

— Recipes

Copy, paste, ship.

01

An accessible modal in four hooks

Focus moves in and comes back, the page stops scrolling, Escape and an outside click both close it.

Modal.tsx
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>
  )
}
02

Controlled or uncontrolled, one component

Pass open to control it, or defaultOpen and let it manage itself. onOpenChange fires either way.

Disclosure.tsx
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}
    </>
  )
}
03

Search that waits for a pause

The input stays instant; the request only follows the debounced value. Recent queries persist across reloads and tabs.

Search.tsx
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/core
Sources · 43 claims, each traced to v2.9.1 code or docs
  1. Hook count 36 is facts.hooks, counted from the published type declarationssite:src/lib/facts.ts
  2. All hooks exported from one entry pointui-system:packages/hooks/src/index.ts
  3. useMediaQuery built on useSyncExternalStore; server/hydration render false, client-only renders get the real value firstui-system:packages/hooks/src/useMediaQuery.ts
  4. useMediaQuery keeps one MediaQueryList per query; snapshot is a property readui-system:packages/hooks/src/useMediaQuery.ts
  5. useLocalStorage built on useSyncExternalStore; server/hydration render initialValueui-system:packages/hooks/src/useLocalStorage.ts
  6. useLocalStorage instances with the same key stay in sync within the tab and across tabsui-system:packages/hooks/src/useLocalStorage.ts
  7. useLocalStorage private mode / quota errors keep the value in memoryui-system:packages/hooks/src/useLocalStorage.ts
  8. useLocalStorage returns [value, setValue, remove]ui-system:packages/hooks/src/useLocalStorage.ts
  9. useBreakpoint: one shared rAF-throttled resize listener for every instance; useSyncExternalStoreui-system:packages/hooks/src/useBreakpoint.ts
  10. useBreakpoint server/hydration snapshot is the smallest breakpointui-system:packages/hooks/src/useBreakpoint.ts
  11. useBreakpoint returns undefined without Provider/breakpointsui-system:packages/hooks/src/useBreakpoint.ts
  12. usePageVisibility and useOnlineStatus use useSyncExternalStoreui-system:packages/hooks/src/usePageVisibility.ts
  13. useOnlineStatus uses useSyncExternalStoreui-system:packages/hooks/src/useOnlineStatus.ts
  14. useDebouncedCallback: latest callback, .cancel() and .flush()ui-system:packages/hooks/src/useDebouncedCallback.ts
  15. useThrottledCallback: latest callback, uses core's throttle, cancel on unmountui-system:packages/hooks/src/useThrottledCallback.ts
  16. useInterval: null pauses; latest callbackui-system:packages/hooks/src/useInterval.ts
  17. useTimeout returns reset and clearui-system:packages/hooks/src/useTimeout.ts
  18. useKeyboard calls the latest handlerui-system:packages/hooks/src/useKeyboard.ts
  19. useClickOutside keeps the latest handler; pointerdown once per tap; composedPath for removed targets / shadow DOMui-system:packages/hooks/src/useClickOutside.ts
  20. useEventListener handler captured via ref, listener stays stableui-system:packages/hooks/src/useEventListener.ts
  21. useScrollLock reference-counts concurrent locks; overflow hidden on bodyui-system:packages/hooks/src/useScrollLock.ts
  22. useFocusTrap: focus in on enable, restore on disable (WAI-ARIA dialog), Tab/Shift+Tab cycleui-system:packages/hooks/src/useFocusTrap.ts
  23. useFocusTrap caches focusables, refreshes on DOM mutationsui-system:packages/hooks/src/useFocusTrap.ts
  24. useFocusTrap filters aria-disabled, includes contenteditable and media controlsui-system:packages/hooks/src/useFocusTrap.ts
  25. useFocusTrap leaves visibility (display:none) to the consumerui-system:packages/hooks/src/useFocusTrap.ts
  26. useControllableState: onChange fires in both modesui-system:packages/hooks/src/useControllableState.ts
  27. useElementSize measures the border box with ResizeObserverui-system:packages/hooks/src/useElementSize.ts
  28. useIntersection returns [ref, entry] over IntersectionObserverui-system:packages/hooks/src/useIntersection.ts
  29. useThemeValue deep-reads a dot path from the themeui-system:packages/hooks/src/useThemeValue.ts
  30. useRootSize defaults to 16 without a Providerui-system:packages/hooks/src/useRootSize.ts
  31. useSpacing: spacing(n) from rootSize / 2ui-system:packages/hooks/src/useSpacing.ts
  32. Theme hooks read @vitus-labs/core's contextui-system:packages/hooks/src/useThemeValue.ts
  33. useCopyToClipboard: Clipboard API, execCommand fallback, copied resets after 2000 msui-system:packages/hooks/src/useCopyToClipboard.ts
  34. useMergedRef supports React 19 ref cleanupsui-system:packages/hooks/src/useMergedRef.ts
  35. useColorScheme on native uses Appearanceui-system:packages/hooks/src/useColorScheme.native.ts
  36. useReducedMotion on native uses AccessibilityInfoui-system:packages/hooks/src/useReducedMotion.native.ts
  37. Native index exports 21 hooks; useHover/useFocus intentionally not exportedui-system:packages/hooks/src/index.native.ts
  38. useKeyboard is a no-op on React Nativeui-system:packages/hooks/src/useKeyboard.native.ts
  39. useWindowScroll returns {0,0} on the server and until mountui-system:packages/hooks/src/useWindowScroll.ts
  40. useIsomorphicLayoutEffect: useLayoutEffect on the client, useEffect on the server; avoids the SSR warningui-system:packages/hooks/src/useIsomorphicLayoutEffect.ts
  41. useIsClient false on server and first client renderui-system:packages/hooks/src/useIsClient.ts
  42. Peer dependencies: @vitus-labs/core and react >= 19 (react-native optional)npm:@vitus-labs/hooks/package.json
  43. Published bundle imports @vitus-labs/corenpm:@vitus-labs/hooks/lib/index.js