Skip to content
@pyreon/hooks
fundamentals · hooks

65 hooks. Zero cleanup code to write.

From useToggle and useClickOutside to useShare, useBiometrics and useGeolocation. Each one removes its own listeners, timers and observers when the component unmounts, renders safely on the server, and hands back signals you can read anywhere.

bun add @pyreon/hooks
Documentation
hooks
65 in one packageState, DOM, responsive, timing, device, data, composition.
cleanup
automatic on unmountListeners, observers and timers are removed for you.
server
SSR-safeBrowser APIs are guarded; nothing throws during server rendering.
native
45 of 65 compile to iOS and AndroidCounted on main. Native targets are experimental.
Hooks clean up after themselves Schematic: a component mounts and four hooks attach a document listener, an interval timer, a ResizeObserver and online/offline listeners. When the component unmounts, all four are removed at once; the cleanup code you would write by hand is not needed. 65 HOOKS · LISTENERS, TIMERS AND OBSERVERS REMOVED FOR YOU in the componentattached to the page useClickOutside(() => el, close)document 'pointerdown'removeduseInterval(refresh, 30_000)setInterval timerremoveduseElementSize(() => el)ResizeObserverremoveduseOnline()window online / offlineremoved mount unmount no removeEventListener to write · SSR-safe · returns signals
  • 65 hooks in one package, across seven categoriespackages/fundamentals/hooks/src/index.ts; README.md "65 hooks across 7 categories"
  • 45 of them compile to SwiftUI and Compose apps from the same call (counted on main; native is experimental)nativeLoweredHooks() with first-party plugins ∩ @pyreon/hooks exports, run on main (.scratch/core/fork-c/lowered.ts)
  • 0–6% what a hook costs over the raw signal it wraps (overnight run, one run)BENCHMARKS.md 2026-11-05 §10, hooks row

synthetic · author-run · M3 Max · record of 2026-11-05

Every result, including where we lose →
why teams pick it

The helpers you keep copying from blog posts, done properly once.

  1. Nothing to clean up

    Every listener, observer, interval and timeout is registered against the component and removed on unmount. There is no return () => removeEventListener(…) to forget.

  2. Signals in, signals out

    Stateful hooks return accessors such as online() or visibility(). Pass one to another hook as a getter and it reacts, so useInterval(fn, () => visible() ? 30_000 : null) pauses itself when the tab hides.

  3. The edge cases are already handled

    useScrollLock is reference-counted and pads for the scrollbar so the page does not jump. useClickOutside listens to pointerdown, so one tap fires once. useClipboard ignores a slower, older copy that resolves last.

  4. One call, three platforms

    useShare, useHaptics, useBiometrics, useImagePicker and 41 others compile to native code for iOS and Android. Three are web-only by design (useBreakpoint, a width useMediaQuery, useControllableState): a native build drops them with a named warning instead of guessing.

the difference

Pause polling while nobody is looking.

React · hand-rolled

A visibility hook, a ref so the interval sees the latest callback, and two dependency arrays to keep right.

import { useEffect, useRef, useState } from 'react'

function useVisible() {
  const [visible, setVisible] = useState(
    typeof document === 'undefined' || document.visibilityState === 'visible',
  )
  useEffect(() => {
    const onChange = () => setVisible(document.visibilityState === 'visible')
    document.addEventListener('visibilitychange', onChange)
    return () => document.removeEventListener('visibilitychange', onChange)
  }, [])
  return visible
}

export function Prices({ refresh }: { refresh: () => void }) {
  const visible = useVisible()
  const latest = useRef(refresh)
  useEffect(() => {
    latest.current = refresh
  }, [refresh])

  useEffect(() => {
    if (!visible) return
    const id = setInterval(() => latest.current(), 30_000)
    return () => clearInterval(id)
  }, [visible])

  return <p>Refreshing every 30 s while you're looking.</p>
}
Pyreon · @pyreon/hooks

The delay is a getter. When the tab hides it returns null and the interval stops; when it comes back, it restarts. Unmount clears it.

import { useDocumentVisibility, useInterval } from '@pyreon/hooks'

export function Prices(props: { refresh: () => void }) {
  const visibility = useDocumentVisibility()

  useInterval(
    () => props.refresh(),
    () => (visibility() === 'visible' ? 30_000 : null),
  )

  return <p>Refreshing every 30 s while you're looking.</p>
}
coming from

Coming from react-use or usehooks-ts?

useClickAway → useClickOutside

react-use
import { useRef, useState } from 'react'
import { useClickAway } from 'react-use'

export function Menu() {
  const [open, setOpen] = useState(true)
  const ref = useRef<HTMLDivElement>(null)
  useClickAway(ref, () => setOpen(false))
  return open ? <div ref={ref}>Menu</div> : null
}
Pyreon

The element is passed as a getter, so it can mount and unmount while the listener stays in place.

import { signal } from '@pyreon/reactivity'
import { useClickOutside } from '@pyreon/hooks'

export function Menu() {
  const open = signal(true)
  const panel = signal<HTMLElement | null>(null)
  useClickOutside(() => panel(), () => open.set(false))
  return () => (open() ? <div ref={(el) => panel.set(el)}>Menu</div> : null)
}

useMediaQuery returns an accessor

usehooks-ts
import { useMediaQuery } from 'usehooks-ts'

export function Layout() {
  const wide = useMediaQuery('(min-width: 768px)')
  return <div>{wide ? 'Sidebar layout' : 'Stacked layout'}</div>
}
Pyreon

In React the whole component re-renders when the query flips. Here only the text node that reads wide() updates.

import { useMediaQuery } from '@pyreon/hooks'

export function Layout() {
  const wide = useMediaQuery('(min-width: 768px)')
  return <div>{() => (wide() ? 'Sidebar layout' : 'Stacked layout')}</div>
}
try it

Try a few, live.

These read your browser right now: go offline, switch the colour scheme, resize the window, switch tabs. Browse all 65 beside them.

useOnline()…
useColorScheme()…
useWindowResize()…
useDocumentVisibility()…
useIdle(3000)…
useTimeAgo(loaded)…
all hooks · 65

state · 5

  • useToggle
  • useCounter
  • usePrevious
  • useLatest
  • useControllableState

DOM · 13

  • useEventListener
  • useClickOutside
  • useFocus
  • useHover
  • useFocusTrap
  • useFocusReturn
  • useInertOthers
  • useElementSize
  • useWindowResize
  • useWindowScroll
  • useScrollLock
  • useIntersection
  • useInfiniteScroll

responsive · 5

  • useBreakpoint
  • useMediaQuery
  • useColorScheme
  • useSizeClass
  • useReducedMotion

timing · 6

  • useDebouncedValue
  • useDebouncedCallback
  • useThrottledCallback
  • useInterval
  • useTimeout
  • useTimeAgo

device · 24

  • useClipboard
  • useHaptics
  • useShare
  • useLinking
  • useNotifications
  • useBiometrics
  • useImagePicker
  • useFilePicker
  • useCamera
  • useAudioRecorder
  • useBluetooth
  • useWakeLock
  • useSpeech
  • useDeviceMotion
  • useScreenOrientation
  • useSafeArea
  • useDeviceInfo
  • useKeyboard
  • useOnline
  • useAppState
  • useDocumentVisibility
  • useIdle
  • useDialog
  • useCrashReporter

data · 9

  • useFetch
  • useAuth
  • useDatabase
  • useGeolocation
  • useMap
  • useWebSocket
  • useSecureStorage
  • usePush
  • usePayments

composition · 3

  • useMergedRef
  • useUpdateEffect
  • useIsomorphicLayoutEffect
benchmarks

A faster counter than Solid's or Preact's. The hook layer costs 0–6%.

useCounter increments 1.27× faster than a Solid signal counter and 1.47× faster than a Preact Signals one, and the wrapper measures 0–6% over the raw signal it returns. Synthetic, author-run, one overnight run under bun.

vs Solid and Preact counters · bun/JavaScriptCorePyreonrival · lower is better
  • hook overhead vs a raw signal
    measured0–6%
  • counter vs Solid createSignal
    win1.27× faster (one run)
  • counter vs Preact Signals
    win1.47× faster (one run)
Apple M3 Max · record of 2026-11-05 · overnight run, one run · author-run, syntheticFull method, every loss →
what's included

Seven categories, one package.

  • State: useToggle, useCounter, usePrevious, useLatest, useControllableState
  • DOM: click outside, hover, focus, element size, intersection, infinite scroll, scroll lock
  • Focus for overlays: useFocusTrap stacks nested modals; useInertOthers makes the background inert and restores it exactly
  • Responsive: useMediaQuery, useColorScheme, useSizeClass, useReducedMotion, useBreakpoint
  • Timing: debounced values and callbacks, throttling, intervals with a reactive delay, a self-updating useTimeAgo
  • Device: clipboard, haptics, share sheet, notifications, biometrics, camera, image and file pickers, speech, wake lock
  • Data: useFetch aborts the previous request on refetch and on unmount, so a slow response never overwrites a fresh one
  • Cross-platform state: useAuth, useDatabase, useMap, usePush, usePayments mirror their native containers field for field
  • Secrets stay off disk: useSecureStorage uses the Keychain on iOS, AndroidKeyStore on Android, and memory only on the web
  • Newly native:next release useDocumentVisibility, usePrevious, useUpdateEffect, useReducedMotion, useKeyboard, useLatest and prefers-color-scheme queries now compile for iOS and Android
recipes

Things to build with it.

A dialog that behaves

Focus moves in and stays in, the page behind stops scrolling, Escape and a click outside both close it. Four hooks, no cleanup code.

import { effect, signal } from '@pyreon/reactivity'
import { useClickOutside, useFocusTrap, useKeyboard, useScrollLock } from '@pyreon/hooks'

export function Dialog(props: { open: () => boolean; onClose: () => void }) {
  const panel = signal<HTMLElement | null>(null)
  const scroll = useScrollLock()

  useFocusTrap(() => panel(), { active: () => props.open(), initialFocus: true })
  useClickOutside(() => panel(), () => props.onClose())
  useKeyboard('Escape', () => props.onClose())
  effect(() => (props.open() ? scroll.lock() : scroll.unlock()))

  return () =>
    props.open() ? (
      <div ref={(el) => panel.set(el)} role="dialog" aria-modal="true">
        <input placeholder="Name" />
        <button onClick={() => props.onClose()}>Close</button>
      </div>
    ) : null
}
Polling that stops when nobody is watching

Refresh every 10 seconds, pause while the tab is hidden or the network is down, and show a label that keeps itself current.

import { signal } from '@pyreon/reactivity'
import { useDocumentVisibility, useInterval, useOnline, useTimeAgo } from '@pyreon/hooks'

export function LiveScore(props: { load: () => Promise<number> }) {
  const score = signal(0)
  const updated = signal(Date.now())
  const visibility = useDocumentVisibility()
  const online = useOnline()

  const refresh = async () => {
    score.set(await props.load())
    updated.set(Date.now())
  }

  // Polls every 10 s, pauses while the tab is hidden or the network is gone.
  useInterval(refresh, () => (visibility() === 'visible' && online() ? 10_000 : null))
  const ago = useTimeAgo(() => updated())

  return (
    <p>
      {() => score()} · updated {() => ago()}
      {() => (online() ? null : ' · offline, paused')}
    </p>
  )
}
One share button for web, iPhone and Android

The share sheet where there is one, the clipboard where there is not, and a light tap of haptic feedback. useShare and useHaptics compile to the platform APIs in a native build.

import { useClipboard, useHaptics, useShare } from '@pyreon/hooks'
import { Button } from '@pyreon/primitives'

export function ShareButton(props: { url: string }) {
  const share = useShare()
  const clipboard = useClipboard()
  const haptics = useHaptics()

  const onPress = async () => {
    haptics.impact('light')
    if (share.canShare()) share.url(props.url)
    else await clipboard.copy(props.url)
  }

  return (
    <Button onPress={onPress}>
      {clipboard.copied() ? 'Link copied' : 'Share'}
    </Button>
  )
}
api

65 hooks.

Every export has a reference page with its signature, an example and the mistakes people make with it.

state · 5
  • useToggle
  • useCounter
  • usePrevious
  • useLatest
  • useControllableState
DOM · 13
  • useEventListener
  • useClickOutside
  • useFocus
  • useHover
  • useFocusTrap
  • useFocusReturn
  • useInertOthers
  • useElementSize
  • useWindowResize
  • useWindowScroll
  • useScrollLock
  • useIntersection
  • useInfiniteScroll
responsive · 5
  • useBreakpoint
  • useMediaQuery
  • useColorScheme
  • useSizeClass
  • useReducedMotion
timing · 6
  • useDebouncedValue
  • useDebouncedCallback
  • useThrottledCallback
  • useInterval
  • useTimeout
  • useTimeAgo
device and interaction · 24
  • useClipboard
  • useHaptics
  • useShare
  • useLinking
  • useNotifications
  • useBiometrics
  • useImagePicker
  • useFilePicker
  • useCamera
  • useAudioRecorder
  • useBluetooth
  • useWakeLock
  • useSpeech
  • useDeviceMotion
  • useScreenOrientation
  • useSafeArea
  • useDeviceInfo
  • useKeyboard
  • useOnline
  • useAppState
  • useDocumentVisibility
  • useIdle
  • useDialog
  • useCrashReporter
data · 9
  • useFetch
  • useAuth
  • useDatabase
  • useGeolocation
  • useMap
  • useWebSocket
  • useSecureStorage
  • usePush
  • usePayments
composition · 3
  • useMergedRef
  • useUpdateEffect
  • useIsomorphicLayoutEffect
good to know

Good to know before you start.

Device hooks ask for permission

Camera, notifications, location and the microphone prompt the user and can be refused. useAudioRecorder().start() and useDeviceMotion().start() resolve false on a refusal, so a denial is an if, not a try.

Web APIs vary by browser

Web Bluetooth, the Share API and wake lock are not in every browser. Check the hook's own flag first: canShare() on useShare, available() on useBluetooth, supported() on useWakeLock.

Native lowering is experimental

Hooks that compile to iOS and Android follow the native compiler's status. Some take a narrower shape natively (a literal key for useKeyboard, a string URL for useFetch); anything else is a named warning.

questions

What people ask first.

Do I still write dependency arrays?

No. A hook reads signals, so it knows what it depends on. useUpdateEffect(source, callback) takes a getter, which is the opposite order from React's (effect, deps).

What happens during server rendering?

Browser APIs are guarded, so a hook renders its server value (for example useOnline() is true, useDocumentVisibility() is "visible"). useFetch starts pending on the server too, so the hydrated page matches the server HTML.

Which hooks work on iOS and Android?

45 of the 65 compile to native code. The DOM-only ones (focus traps, element size, scroll lock and similar) stay on the web, and three are web-only by design with a named compile warning: useBreakpoint, a width or orientation useMediaQuery, and useControllableState. Use useSizeClass() for compact versus regular layouts on every platform.

Does importing one hook pull in all 65?

No. The package is ESM and marked side-effect free, so a bundler keeps only the hooks you import.

Is useFetch a replacement for a data library?

It is deliberately thin: one request, abort on refetch and unmount, no cache, no retries. For caching and signal-driven keys use @pyreon/query.

Stop rewriting useEventListener in every project. We wrote it 65 times so you don't have to.

bun add @pyreon/hooks
Read the hooks guide