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 - 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.
- 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 →The helpers you keep copying from blog posts, done properly once.
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.Signals in, signals out
Stateful hooks return accessors such as
online()orvisibility(). Pass one to another hook as a getter and it reacts, souseInterval(fn, () => visible() ? 30_000 : null)pauses itself when the tab hides.The edge cases are already handled
useScrollLockis reference-counted and pads for the scrollbar so the page does not jump.useClickOutsidelistens topointerdown, so one tap fires once.useClipboardignores a slower, older copy that resolves last.One call, three platforms
useShare,useHaptics,useBiometrics,useImagePickerand 41 others compile to native code for iOS and Android. Three are web-only by design (useBreakpoint, a widthuseMediaQuery,useControllableState): a native build drops them with a named warning instead of guessing.
Pause polling while nobody is looking.
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>
}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 react-use or usehooks-ts?
useClickAway → useClickOutside
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
}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
import { useMediaQuery } from 'usehooks-ts'
export function Layout() {
const wide = useMediaQuery('(min-width: 768px)')
return <div>{wide ? 'Sidebar layout' : 'Stacked layout'}</div>
}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 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.
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
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.
- hook overhead vs a raw signalmeasured0–6%
- counter vs Solid createSignalwin1.27× faster (one run)
- counter vs Preact Signalswin1.47× faster (one run)
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-schemequeries now compile for iOS and Android
Things to build with it.
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
}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>
)
}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>
)
}65 hooks.
Every export has a reference page with its signature, an example and the mistakes people make with it.
- useToggle
- useCounter
- usePrevious
- useLatest
- useControllableState
- useEventListener
- useClickOutside
- useFocus
- useHover
- useFocusTrap
- useFocusReturn
- useInertOthers
- useElementSize
- useWindowResize
- useWindowScroll
- useScrollLock
- useIntersection
- useInfiniteScroll
- useBreakpoint
- useMediaQuery
- useColorScheme
- useSizeClass
- useReducedMotion
- useDebouncedValue
- useDebouncedCallback
- useThrottledCallback
- useInterval
- useTimeout
- useTimeAgo
- useClipboard
- useHaptics
- useShare
- useLinking
- useNotifications
- useBiometrics
- useImagePicker
- useFilePicker
- useCamera
- useAudioRecorder
- useBluetooth
- useWakeLock
- useSpeech
- useDeviceMotion
- useScreenOrientation
- useSafeArea
- useDeviceInfo
- useKeyboard
- useOnline
- useAppState
- useDocumentVisibility
- useIdle
- useDialog
- useCrashReporter
- useFetch
- useAuth
- useDatabase
- useGeolocation
- useMap
- useWebSocket
- useSecureStorage
- usePush
- usePayments
- useMergedRef
- useUpdateEffect
- useIsomorphicLayoutEffect
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.
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.
Built to be used together.
Primitives
The cross-platform UI these hooks pair with.
Native
Where 45 of these hooks compile to SwiftUI and Compose.
Hotkeys
Shortcuts with modifiers, beyond useKeyboard.
Accessibility
Announcements to go with the focus traps.
Stop rewriting useEventListener in every project. We wrote it 65 times so you don't have to.
bun add @pyreon/hooks