Command palette

@yasinsensoy/native

React Native · APIs and utilities

Hooks

Writes text to the clipboard and keeps a "copied" state for a short while (same API as useClipboard on web).

18 exports

Import

import {
  useClipboard,
  useControllableState,
  useDebounce,
  useDebouncedCallback,
  useDisclosure,
  useScrollTracker,
  useScrollValue,
} from "@yasinsensoy/native";

useClipboard

function

Writes text to the clipboard and keeps a "copied" state for a short while (same API as useClipboard on web). Uses the library's own clipboard module.

For a ready-made button see CopyButton.

useClipboard(options?: UseClipboardOptions): UseClipboardResult

Examples

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

// One-time code: hidden in the preview, removed after 60 s
const code = useClipboard({ sensitive: true, expiresIn: 60_000 });

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 sending 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]);

A debounced version of a function. The returned function is stable; even if the inner function changes on every render, the current 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 every 100 ms while scrolling
const track = useDebouncedCallback(savePosition, 100, { maxWait: 100 });

State of anything that opens and closes (Dialog, Sheet, Popover, Collapsible, menus). 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?" onConfirm={remove} />

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

Tracks the offset and direction of a scrollable component without re-rendering the component that renders it. Fab (scrollBehavior) and BackToTop subscribe to it; only they re-render. On web the browser's scroll event does this; on native the scroll component must be bound explicitly.

useScrollTracker(): ScrollTracker

Examples

const scroll = useScrollTracker();
<View style={{ flex: 1 }}>
  <ScrollView ref={scroll.ref} onScroll={scroll.onScroll} scrollEventThrottle={16}>…</ScrollView>
  <Fab label="New" scroll={scroll} scrollBehavior="hide" />
  <BackToTop scroll={scroll} />
</View>

Reads a value selected from a ScrollTracker; re-renders only when that value changes (e.g. (s) => s.away). An empty state without a tracker.

useScrollValue(tracker: ScrollTracker | undefined, select: (state: ScrollTrackerState) => T): T

Value to write to the clipboard (the same type as web): plain text or rich content. The mobile clipboard does not carry formatting; text is copied.

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 does not reset by itself.
sensitive?booleanfalseSensitive data (password, one-time code): hidden in the preview on Android 13+, not sent to other devices on iOS. See ClipboardSetOptions.
expiresIn?numberRemoved from the clipboard after this many ms (if the user has not copied something else).
onCopy?(text: string) => voidCalled when copying succeeds.
onError?(error: unknown) => voidCalled when copying fails.

Value returned by the useClipboard hook.

NameTypeDescription
copy(value: ClipboardValue | (() => ClipboardValue | Promise<ClipboardValue>)) => Promise<boolean>Writes a value to the clipboard; returns true on success. The value can also be a function or a Promise (e.g. a share link from the server).
copiedbooleanThe last copy succeeded and the timeout has not passed.
errorunknownError of the last copy; null after a successful copy.
reset() => voidResets copied and error.

Options of the useControllableState hook.

NameTypeDescription
value?T | undefinedValue given from outside. When not undefined the component is 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?numberRuns at least once within this time (ms) even if calls never stop. Given the same as delay, it becomes a throttle: for scrolling, resizing, pointer tracking.

The function returned by the useDebouncedCallback hook.

NameTypeDescription
cancel() => voidCancels the pending call.
flush() => voidRuns the pending call immediately (e.g. save when leaving the page).
pending() => booleanWhether a call is pending.

Options of the useDisclosure hook.

NameTypeDefaultDescription
defaultOpen?booleanfalseOpen initially?
open?booleanState managed from outside; when given the hook is controlled.
onOpenChange?(open: boolean) => voidCalled whenever the state changes.

Value returned by the useDisclosure hook.

NameTypeDescription
openbooleanWhether it is 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 overlay components: <Dialog {...modal.props}>, <Sheet {...panel.props}>.

Scrollable

interface

Reference of a scrollable component: ScrollView, FlatList, VirtualList…

NameTypeDescription
scrollTo?(options: { x?: number; y?: number; animated?: boolean; }) => voidScrollView scroll method.
scrollToOffset?(options: { offset: number; animated?: boolean; }) => voidFlatList scroll method.

Snapshot state of a ScrollTracker.

NameTypeDescription
ynumberScroll offset (vertical, dp).
viewportnumberHeight of the visible area.
contentnumberTotal height of the content.
direction"up" | "down" | "none"Last significant scroll direction.
awaybooleanWhether the user scrolled down into the content (false when scrolling up or returning to the top). The Fab's hiding/shrinking uses this.

ScrollTracker

interface

Result of useScrollTracker: passed to the scrollable component and to the trackers.

NameTypeDescription
ref{ current: Scrollable | null; }ref of the scrollable component (to scroll back to the top).
onScroll(event: NativeSyntheticEvent<NativeScrollEvent>) => voidonScroll of the scrollable component; use it with scrollEventThrottle={16}.
get() => ScrollTrackerStateSnapshot state (does not trigger a render).
subscribe(listener: (state: ScrollTrackerState) => void) => () => voidCalled when the state changes; returns a function that ends the subscription.
scrollTo(y?: number, animated?: boolean) => voidScrolls to the top (or to y).