Command palette

@yasinsensoy/web

Web · APIs and utilities

Hooks

Closes an open layer (Dialog, Sheet, menu…) with the browser's or phone's back button.

38 exports

Live example

Preview

or Control+J (useHotkeys)

Hello

Opened with useDisclosure.

Debounced value: “”
Refresh or open a new tab; the value stays.
useResizeObserver: 0 px (resize from the bottom right)

Scroll down…

useIntersection: not visible

Code

const modal = useDisclosure();
const gecikmeli = useDebounce(search, 400);
const [counter, setCounter, remove] = useLocalStorage("counter", 0);
const { copy, copied } = useClipboard();
const { ref, width } = useResizeObserver();
const { ref: gorRef, inView } = useIntersection({ once: true });
useHotkeys("Mod+J", modal.toggle);

Events

  1. Events appear here when you interact with the preview.

Import

import {
  useBackButtonClose,
  useClipboard,
  useControllableState,
  useDebounce,
  useDebouncedCallback,
  useDisclosure,
  useHotkeys,
  useIntersection,
  useKeyboardInset,
  useLocalStorage,
  useSessionStorage,
  useMediaQuery,
  usePrefersReducedMotion,
  OVERLAY_SCROLLBAR_QUERY,
  useOverlayScrollbar,
  useResizeObserver,
  useSwipeToClose,
} from "@yasinsensoy/web";

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

useBackButtonClose(open: boolean, onClose: () => void): void

Examples

"use client";
function Menu() {
  const [open, setOpen] = useState(false);
  useBackButtonClose(open, () => setOpen(false));
  return open ? <nav>...</nav> : null;
}

useClipboard

function

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

useClipboard(options?: UseClipboardOptions): UseClipboardResult

Examples

const { copy, copied } = useClipboard();
<Button onClick={() => copy(apiKey)}>{copied ? "Copied" : "Copy key"}</Button>

// Rich: pastes as a link into email, as a URL into a text editor
copy({ text: url, html: `<a href="${url}">${title}</a>` });

// A value from the server
copy(() => createShareLink(id));

State management for components usable both controlled (value + onChange) and uncontrolled (defaultValue). Gives the same behavior everywhere, like Dialog's open or Tabs' value prop.

useControllableState({ value, defaultValue, onChange, }: UseControllableStateOptions<T>): [T, (next: SetStateAction<T>) => void]

Examples

function Switch({ checked, defaultChecked = false, onCheckedChange }: SwitchProps) {
  const [isOn, setIsOn] = useControllableState({
    value: checked,
    defaultValue: defaultChecked,
    onChange: onCheckedChange,
  });
  return <button aria-pressed={isOn} onClick={() => setIsOn((v) => !v)} />;
}

useDebounce

function

A copy of the value updated delay ms after its last change. To avoid a request on every keystroke in a search box.

useDebounce(value: T, delay?: number): T

Examples

const [query, setQuery] = useState("");
const debounced = useDebounce(query, 300);
useEffect(() => { search(debounced); }, [debounced]);

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

useDebouncedCallback(callback: (...args: Args) => unknown, delay?: number, options?: UseDebouncedCallbackOptions): DebouncedFunction<Args>

Examples

const save = useDebouncedCallback((text: string) => saveDraft(text), 800);
<TextField multiline onChange={(e) => save(e.target.value)} onBlur={save.flush} />

// Throttle: at most once per 100 ms while scrolling
const track = useDebouncedCallback(savePosition, 100, { maxWait: 100 });

State of anything that opens and closes (Dialog, Sheet, Popover, Collapsible, menu). Instead of writing useState(false) + three separate functions.

useDisclosure(options?: UseDisclosureOptions): UseDisclosureResult

Examples

const deletion = useDisclosure();
<Button onClick={deletion.show}>Delete</Button>
<Dialog {...deletion.props} title="Delete it?" onConfirm={remove} />

const filters = useDisclosure({ defaultOpen: true });
<Button onClick={filters.toggle}>{filters.open ? "Hide" : "Filters"}</Button>

useHotkeys

function

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

useHotkeys(keys: string | readonly string[] | Readonly<Record<string, HotkeyHandler>>, handler?: HotkeyHandler | UseHotkeysOptions, options?: UseHotkeysOptions): void

Examples

useHotkeys("Mod+K", () => palette.show());
useHotkeys(["Mod+S", "Mod+Enter"], () => save());
useHotkeys({
  "G D": () => router.push("/dashboard"),
  "?": () => help.show(),
  Escape: () => clearSelection(),
});

// Only while the editor is focused, in text fields too
useHotkeys("Mod+B", bold, { target: editorRef, enableInInputs: true });

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

useIntersection(options?: UseIntersectionOptions): UseIntersectionResult<E>

Examples

const { ref, inView } = useIntersection<HTMLDivElement>({ once: true, rootMargin: "200px" });
<div ref={ref}>{inView ? <HeavyChart /> : <Skeleton className="h-64" />}</div>

// Visible ratio
const { ref, entry } = useIntersection({ threshold: [0, 0.5, 1] });
const ratio = entry?.intersectionRatio ?? 0;

Writes 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)].

useKeyboardInset(ref: RefObject<HTMLElement | null>, enabled?: boolean): void

Examples

const ref = useRef<HTMLDivElement>(null);
useKeyboardInset(ref, open);
return <div ref={ref} className="fixed inset-x-0 bottom-[var(--ui-keyboard-inset,0px)]" />;

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

useLocalStorage(key: string, initialValue: T, options?: UseLocalStorageOptions<T>): UseLocalStorageResult<T>

Examples

const [dense, setDense] = useLocalStorage("list-dense", false);
<Switch checked={dense} onCheckedChange={setDense} label="Compact view" />

const [cart, setCart, clear] = useLocalStorage<Product[]>("cart", []);
setCart((c) => [...c, product]);

The sessionStorage version of useLocalStorage: the value is cleared when the tab closes (e.g. a form's unfinished step, a tab-specific filter).

useSessionStorage(key: string, initialValue: T, options?: Omit<UseLocalStorageOptions<T>, "storage">): UseLocalStorageResult<T>

Examples

const [step, setStep] = useSessionStorage("signup-step", 0);

Tracks 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).

useMediaQuery(query: string, serverValue?: boolean): boolean

Examples

const desktop = useMediaQuery("(min-width: 768px)");
const touch = useMediaQuery("(pointer: coarse)");

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

usePrefersReducedMotion(): boolean

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

OVERLAY_SCROLLBAR_QUERY: none)"

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

useOverlayScrollbar(viewport: RefObject<HTMLElement | null> | "page", { y, x, enabled }: UseOverlayScrollbarOptions): void

Examples

const viewport = useRef<HTMLDivElement>(null);
const y = useRef<HTMLDivElement>(null);
useOverlayScrollbar(viewport, { y });

<div className="relative">
  <div ref={viewport} data-overlay-scrollbar className="h-64 overflow-auto">…</div>
  <div ref={y} aria-hidden className="absolute …"><div className="…" /></div>
</div>

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

useResizeObserver(options?: UseResizeObserverOptions): UseResizeObserverResult<E>

Examples

const { ref, width = 0 } = useResizeObserver<HTMLDivElement>();
<div ref={ref}>{width < 400 ? <ShortSummary /> : <Table />}</div>

// Render-free: redraw the canvas
const { ref } = useResizeObserver<HTMLCanvasElement>({
  onResize: ({ width, height }) => draw(width, height),
});

Lets 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, onClose is 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.

useSwipeToClose(ref: RefObject<HTMLElement | null>, { direction, onClose, enabled, threshold }: UseSwipeToCloseOptions): void

Examples

const ref = useRef<HTMLDivElement>(null);
useSwipeToClose(ref, { direction: "down", enabled: open, onClose: () => setOpen(false) });

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

type ClipboardValue = string | { text: string; html?: string; }

Options of the useClipboard hook.

NameTypeDefaultDescription
timeout?number2000After how many ms copied returns to false. With 0 it doesn't return by itself.
onCopy?(text: string) => voidCalled when copying succeeds.
onError?(error: unknown) => voidCalled when copying fails (no permission, unsupported).

Value returned by the useClipboard hook.

NameTypeDescription
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.
copiedbooleanThe last copy succeeded and timeout hasn't elapsed.
errorunknownError of the last copy; null on a successful copy.
reset() => voidResets copied and error.

Options of the useControllableState hook.

NameTypeDescription
value?T | undefinedValue given from outside. If not undefined, the component runs controlled.
defaultValueTInitial value in uncontrolled use.
onChange?((value: T) => void) | undefinedCalled whenever the value changes; in both controlled and uncontrolled use.

Options of the useDebouncedCallback hook.

NameTypeDefaultDescription
leading?booleanfalseRun immediately on the first call, then stay silent during the wait.
trailing?booleantrueRun with the last call when the wait ends.
maxWait?numberEven 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.

Function returned by the useDebouncedCallback hook.

NameTypeDescription
cancel() => voidCancels the pending call.
flush() => voidRuns the pending call right away (e.g. save when leaving the page).
pending() => booleanIs there a pending call?

Options of the useDisclosure hook.

NameTypeDefaultDescription
defaultOpen?booleanfalseWhether it starts open.
open?booleanState managed from outside; if given the hook runs controlled.
onOpenChange?(open: boolean) => voidCalled whenever the state changes.

Value returned by the useDisclosure hook.

NameTypeDescription
openbooleanIs it open?
setOpen(open: boolean) => voidSets the state directly.
show() => voidOpens. Stable; no need to add it to dependency lists.
hide() => voidCloses. Stable.
toggle() => voidCloses 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}>.

Function called when a shortcut fires.

type HotkeyHandler = (event: KeyboardEvent) => void

Options of the useHotkeys hook.

NameTypeDefaultDescription
enabled?booleantrueIf 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?booleanfalseShould 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?booleantruePrevent the browser's own action for this key (e.g. saving the page on Mod+S).
repeat?booleanfalseWhether it repeats while the key is held.
event?"keydown" | "keyup""keydown"Event to listen to.
sequenceTimeout?number1000Maximum wait between steps of a key sequence ("G D") (ms).

Options of the useIntersection hook.

NameTypeDefaultDescription
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[]0How 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?booleanfalseStop tracking after the first appearance (inView stays true): lazy loading, an animation that plays once on first appearance.
initialInView?booleanfalseinView value on the server and the first render.
enabled?booleantrueNot tracked if false.
onChange?(inView: boolean, entry: IntersectionObserverEntry) => voidCalled 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.

Value returned by the useIntersection hook.

NameTypeDescription
ref(element: E | null) => voidGive it to the element to track: <div ref={ref}>.
inViewbooleanIs the element currently visible (by the threshold)?
entryIntersectionObserverEntry | undefinedThe last measurement (visible ratio, boxes); undefined if not measured yet.

Functions converting the value to stored text and back.

NameTypeDescription
stringify(value: T) => stringConverts the value to text.
parse(raw: string) => TConverts text to the value; may throw on corrupt data (the initial value is used).

Options of the useLocalStorage hook.

NameTypeDefaultDescription
storage?"local" | "session""local"Storage location: local is persistent, session is cleared when the tab closes.
serializer?StorageSerializer<T>JSONMethod for converting the value to text.
sync?booleantrueShould 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.

type UseLocalStorageResult = [ value: T, setValue: (next: SetStateAction<T>) => void, remove: () => void ]

Options of the useOverlayScrollbar hook.

NameTypeDefaultDescription
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?booleantrueDoes nothing if false.

ElementSize

interface

Measured size.

NameTypeDescription
widthnumberWidth (px).
heightnumberHeight (px).

Options for the useResizeObserver hook.

NameTypeDefaultDescription
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) => voidCalled 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?booleantrueWhen false, nothing is observed.

Return value of the useResizeObserver hook.

NameTypeDescription
ref(element: E | null) => voidAttach to the element to observe: <div ref={ref}>.
widthnumber | undefinedWidth (px); undefined if not measured yet or onResize was given.
heightnumber | undefinedHeight (px); undefined if not measured yet or onResize was given.

Swipe direction: the direction the element moves while closing.

type SwipeDirection = "up" | "down" | "left" | "right"

Options for the useSwipeToClose hook.

NameTypeDefaultDescription
directionSwipeDirection | falseDirection the finger must swipe to close. false disables it.
onClose() => voidCalled when the threshold is passed; should close the layer.
enabled?booleantrueListens only while true.
threshold?number0.3Fraction of the element's size that must be swiped to close (0–1). A quick flick closes it even before reaching this threshold.