Web · APIs and utilities
Hooks
Closes an open layer (Dialog, Sheet, menu…) with the browser's or phone's back button.
Live example
Preview
Scroll down…
Code
Events
- Events appear here when you interact with the preview.
Import
useBackButtonClose
functionCloses an open layer (Dialog, Sheet, menu…) with the browser's or phone's back button.
Mobile users expect to close popups with the back button/gesture; without this hook the back button goes to the previous page and the user loses the page they are on. When the layer opens an entry (with the same URL) is added to history; the back button consumes it and closes the layer. If the layer closes another way (button, Esc, outside click) the added entry is undone, so no extra step is left in history. When it closes because a link inside it was followed, the entry is kept so that the router's navigation is not cancelled.
With nested layers each back press closes only the topmost. The Next.js App Router's history state is preserved.
Examples
useClipboard
functionWrites text to the clipboard and keeps a "copied" state briefly. Without the Clipboard API (http, old browser) it falls back to the legacy method. If the value is computed lazily (a link from the server) pass a function or a Promise; Safari's "user gesture" requirement is preserved.
For a ready-made button see CopyButton.
Examples
useControllableState
functionState management for components usable both controlled (value + onChange) and uncontrolled (defaultValue). Gives the same behavior everywhere, like Dialog's open or Tabs' value prop.
Examples
useDebounce
functionA copy of the value updated delay ms after its last change. To avoid a request on every keystroke in a search box.
Examples
useDebouncedCallback
functionDebounced version of a function. The returned function is stable; even if the inner function changes on every render the latest one is called. The pending call is cancelled when the component unmounts.
Examples
useDisclosure
functionState of anything that opens and closes (Dialog, Sheet, Popover, Collapsible, menu). Instead of writing useState(false) + three separate functions.
Examples
useHotkeys
functionListens for keyboard shortcuts. The notation matches Kbd and menu shortcuts: "Mod+K" (⌘ on macOS, Ctrl elsewhere), "Mod+Shift+P", "Alt+Enter", "Escape", "?", a key sequence "G D". On non-US keyboard layouts and with letters changed by Alt/Option the physical key is used.
Handlers may change on every render; the listener isn't reattached. To show the shortcut to the user use <Kbd keys="Mod+K" />; for a menu item's shortcut use the item's shortcut prop, not this hook.
Examples
useIntersection
functionTracks whether an element is visible on screen (or in a scroll area). For lazy loading, animations that play on appearance, "read" receipts, a sticky header's shadow. All hooks with the same settings share one observer.
For an infinite list there is the ready-made InfiniteScroll, for a virtual list VirtualList; don't write these by hand.
Examples
useKeyboardInset
functionWrites the height hidden at the bottom of the screen while the mobile keyboard is open to the element as the --ui-keyboard-inset CSS variable.
iOS Safari doesn't shrink the page layout when the keyboard opens; elements fixed to the bottom of the screen (bottom sheets, chat boxes) end up behind the keyboard. With this variable the element can be pushed above the keyboard: mb-[var(--ui-keyboard-inset,0px)].
Examples
useLocalStorage
functionState kept in localStorage (or sessionStorage). Returns the initial value on the server and first hydration, then renders with the stored value; no hydration mismatch. All components using the same key and (sync) other tabs stay in sync. If storage is disabled (private window) or full, it keeps working with the value in memory.
Examples
useSessionStorage
functionThe sessionStorage version of useLocalStorage: the value is cleared when the tab closes (e.g. a form's unfinished step, a tab-specific filter).
Examples
useMediaQuery
functionTracks whether a CSS media query matches.
To change the look, prefer Tailwind's responsive prefixes (sm:, md:) where possible; this hook should be used only when behavior must change (e.g. showing a different component on mobile).
Examples
usePrefersReducedMotion
functionReturns true if the user prefers "reduced motion" in the operating system. In CSS use Tailwind's motion-reduce: prefix; this hook is for animations done in JavaScript.
OVERLAY_SCROLLBAR_QUERY
constantEnvironment where the overlay bar is active: forced colors (Windows high contrast) off. In high contrast the native bar is kept for accessibility. The same bar is drawn for mouse, touchpad and touch screens; so the look is the same on every device. The hiding rule in styles.css uses the same query.
useOverlayScrollbar
functionAttaches a scrollbar to a scrollable area that sits over the content and appears only while scrolling or when the pointer reaches the edge. The bar takes no width; content and page layout don't shift.
In most cases you don't need to use the hook directly: UIProvider sets up the page bar, and ScrollArea (and Dialog, Sheet, Table) set up inner areas themselves.
Tracks (y, x) must be position: absolute and share a positioned ancestor with the scrolled element; the hook places the tracks at the scrolled element's edge itself. Where a wrapper can't be added (e.g. a popup that scrolls itself) tracks can also be rendered inside the positioned scrolled element; the hook keeps them in the visible area while scrolling. If "page" is given as viewport the document itself is tracked; tracks must then be position: fixed and aren't placed.
The scrolled element must carry the data-overlay-scrollbar attribute itself (in the server render too, so the native bar doesn't flash and shift the layout while the page opens); styles.css hides the native bar based on this attribute. If the environment isn't suitable (OVERLAY_SCROLLBAR_QUERY) CSS doesn't hide the native bar and the hook does nothing.
Examples
useResizeObserver
functionObserves an element's size. Use it to change behavior based on the element's own width rather than the screen width (moving overflowing tabs into a menu, redrawing a canvas). All hooks with the same settings share one observer; no re-render happens when the size is unchanged.
For purely visual changes, CSS container queries are faster: <Container query> and @md: classes.
Examples
useSwipeToClose
functionLets a layer be closed by swiping it with a finger on touch screens (e.g. pulling a bottom sheet down, pushing a side menu to the edge).
- The element follows the finger; on release,
onCloseis called if the threshold was passed or a quick flick was made, otherwise it snaps back. - Scrollable areas inside take priority: dragging does not start until the list reaches its start, so normal scrolling is not broken.
- Movements perpendicular to the swipe direction (e.g. scrolling a horizontal gallery) do not count as dragging.
The element's CSS translate property is changed via inline style while dragging; the closing animation continues with the element's own CSS transition.
Examples
ClipboardValue
typeValue to write to the clipboard: plain text or rich content. Rich content pastes with formatting into apps that support html (email, documents) and as text elsewhere.
UseClipboardOptions
interfaceOptions of the useClipboard hook.
| Name | Type | Default | Description |
|---|---|---|---|
timeout? | number | 2000 | After how many ms copied returns to false. With 0 it doesn't return by itself. |
onCopy? | (text: string) => void | Called when copying succeeds. | |
onError? | (error: unknown) => void | Called when copying fails (no permission, unsupported). |
UseClipboardResult
interfaceValue returned by the useClipboard hook.
| Name | Type | Description |
|---|---|---|
copy | (value: ClipboardValue | (() => ClipboardValue | Promise<ClipboardValue>)) => Promise<boolean> | Writes the value to the clipboard; returns true on success. The value can also be a function or a Promise (e.g. a share link fetched from the server); for Safari it starts in the same moment as the user's click. |
copied | boolean | The last copy succeeded and timeout hasn't elapsed. |
error | unknown | Error of the last copy; null on a successful copy. |
reset | () => void | Resets copied and error. |
UseControllableStateOptions
interfaceOptions of the useControllableState hook.
| Name | Type | Description |
|---|---|---|
value? | T | undefined | Value given from outside. If not undefined, the component runs controlled. |
defaultValue | T | Initial value in uncontrolled use. |
onChange? | ((value: T) => void) | undefined | Called whenever the value changes; in both controlled and uncontrolled use. |
UseDebouncedCallbackOptions
interfaceOptions of the useDebouncedCallback hook.
| Name | Type | Default | Description |
|---|---|---|---|
leading? | boolean | false | Run immediately on the first call, then stay silent during the wait. |
trailing? | boolean | true | Run with the last call when the wait ends. |
maxWait? | number | Even if calls never stop, it runs once within this time (ms) at the latest. Given the same as delay it becomes a throttle: for scrolling, resizing, mouse tracking. |
DebouncedFunction
interfaceFunction returned by the useDebouncedCallback hook.
| Name | Type | Description |
|---|---|---|
cancel | () => void | Cancels the pending call. |
flush | () => void | Runs the pending call right away (e.g. save when leaving the page). |
pending | () => boolean | Is there a pending call? |
UseDisclosureOptions
interfaceOptions of the useDisclosure hook.
| Name | Type | Default | Description |
|---|---|---|---|
defaultOpen? | boolean | false | Whether it starts open. |
open? | boolean | State managed from outside; if given the hook runs controlled. | |
onOpenChange? | (open: boolean) => void | Called whenever the state changes. |
UseDisclosureResult
interfaceValue returned by the useDisclosure hook.
| Name | Type | Description |
|---|---|---|
open | boolean | Is it open? |
setOpen | (open: boolean) => void | Sets the state directly. |
show | () => void | Opens. Stable; no need to add it to dependency lists. |
hide | () => void | Closes. Stable. |
toggle | () => void | Closes if open, opens if closed. Stable. |
props | { open: boolean; onOpenChange: (open: boolean) => void; } | Props to spread onto layer components: <Dialog {...modal.props}>, <Sheet {...panel.props}>. |
HotkeyHandler
typeFunction called when a shortcut fires.
UseHotkeysOptions
interfaceOptions of the useHotkeys hook.
| Name | Type | Default | Description |
|---|---|---|---|
enabled? | boolean | true | If false, shortcuts aren't listened to (e.g. while the window is closed). |
target? | RefObject<HTMLElement | null> | Listen only while this element or its descendants are focused. If omitted, it works across the whole page. | |
enableInInputs? | boolean | false | Should it work in text fields too? Default rules: in a text field, keys without modifiers ("/", "G D") and Mod+A/C/V/X/Y/Z don't work, other Mod shortcuts ("Mod+S") do. true enables all. |
preventDefault? | boolean | true | Prevent the browser's own action for this key (e.g. saving the page on Mod+S). |
repeat? | boolean | false | Whether it repeats while the key is held. |
event? | "keydown" | "keyup" | "keydown" | Event to listen to. |
sequenceTimeout? | number | 1000 | Maximum wait between steps of a key sequence ("G D") (ms). |
UseIntersectionOptions
interfaceOptions of the useIntersection hook.
| Name | Type | Default | Description |
|---|---|---|---|
root? | Element | Document | null | { readonly current: Element | null; } | Scroll area visibility is measured against. If omitted, the viewport. A ref or an element can be given. | |
rootMargin? | string | "0px" | Growing/shrinking of the area (like CSS margin): "200px" sets inView 200px before the element becomes visible (preloading). |
threshold? | number | readonly number[] | 0 | How much of the element must be visible for inView (0–1): 0 one pixel, 0.5 half, 1 all. If an array is given, entry updates at each threshold. |
once? | boolean | false | Stop tracking after the first appearance (inView stays true): lazy loading, an animation that plays once on first appearance. |
initialInView? | boolean | false | inView value on the server and the first render. |
enabled? | boolean | true | Not tracked if false. |
onChange? | (inView: boolean, entry: IntersectionObserverEntry) => void | Called when visibility changes. Even if only this is given and inView isn't read, the hook re-renders; with many elements (e.g. read receipts) if you don't want renders, don't use the state, handle it here. |
UseIntersectionResult
interfaceValue returned by the useIntersection hook.
| Name | Type | Description |
|---|---|---|
ref | (element: E | null) => void | Give it to the element to track: <div ref={ref}>. |
inView | boolean | Is the element currently visible (by the threshold)? |
entry | IntersectionObserverEntry | undefined | The last measurement (visible ratio, boxes); undefined if not measured yet. |
StorageSerializer
interfaceFunctions converting the value to stored text and back.
| Name | Type | Description |
|---|---|---|
stringify | (value: T) => string | Converts the value to text. |
parse | (raw: string) => T | Converts text to the value; may throw on corrupt data (the initial value is used). |
UseLocalStorageOptions
interfaceOptions of the useLocalStorage hook.
| Name | Type | Default | Description |
|---|---|---|---|
storage? | "local" | "session" | "local" | Storage location: local is persistent, session is cleared when the tab closes. |
serializer? | StorageSerializer<T> | JSON | Method for converting the value to text. |
sync? | boolean | true | Should this tab update when it changes in another tab? Hooks with the same key in the same tab are always in sync. |
Pair + remove function returned by the useLocalStorage hook.
UseOverlayScrollbarOptions
interfaceOptions of the useOverlayScrollbar hook.
| Name | Type | Default | Description |
|---|---|---|---|
y? | RefObject<HTMLElement | null> | Track of the vertical bar; its first child is the thumb. | |
x? | RefObject<HTMLElement | null> | Track of the horizontal bar; its first child is the thumb. | |
enabled? | boolean | true | Does nothing if false. |
ElementSize
interfaceMeasured size.
| Name | Type | Description |
|---|---|---|
width | number | Width (px). |
height | number | Height (px). |
UseResizeObserverOptions
interfaceOptions for the useResizeObserver hook.
| Name | Type | Default | Description |
|---|---|---|---|
box? | "content-box" | "border-box" | "content-box" | Measured box: content-box is the content without padding, border-box includes borders. |
onResize? | (size: ElementSize, entry: ResizeObserverEntry) => void | Called when the size changes. When provided, the hook keeps no state and does not re-render (width/height stay undefined); useful for render-free work such as redrawing a chart on a canvas. | |
enabled? | boolean | true | When false, nothing is observed. |
UseResizeObserverResult
interfaceReturn value of the useResizeObserver hook.
| Name | Type | Description |
|---|---|---|
ref | (element: E | null) => void | Attach to the element to observe: <div ref={ref}>. |
width | number | undefined | Width (px); undefined if not measured yet or onResize was given. |
height | number | undefined | Height (px); undefined if not measured yet or onResize was given. |
SwipeDirection
typeSwipe direction: the direction the element moves while closing.
UseSwipeToCloseOptions
interfaceOptions for the useSwipeToClose hook.
| Name | Type | Default | Description |
|---|---|---|---|
direction | SwipeDirection | false | Direction the finger must swipe to close. false disables it. | |
onClose | () => void | Called when the threshold is passed; should close the layer. | |
enabled? | boolean | true | Listens only while true. |
threshold? | number | 0.3 | Fraction of the element's size that must be swiped to close (0–1). A quick flick closes it even before reaching this threshold. |