Skip to content

Latest commit

 

History

History
250 lines (171 loc) · 7.6 KB

File metadata and controls

250 lines (171 loc) · 7.6 KB

Hooks Reference

API documentation for all general-purpose hooks included in the template.

At scale: The template ships 11 hooks. In production (Overtooled, 178+ features), this grew to 18 general-purpose hooks plus 4 chain-specific hooks. See Scaling Patterns for details.


useLocalStorage

Persistent state synced to localStorage with cross-instance coordination.

const [value, setValue] = useLocalStorage(key, initialValue);
Param Type Description
key string localStorage key (namespace it: 'myapp:feature:key')
initialValue any Default value if key doesn't exist

Returns: [value, setValue] -- same API as useState. setValue accepts a value or updater function.

Key feature: Multiple components reading the same key stay in sync within the same tab via custom events. No Context needed.


useDebounce

Debounce any value with configurable delay.

const debouncedValue = useDebounce(value, delay);
Param Type Description
value any The value to debounce
delay number Milliseconds to wait (default: 300)

Returns: The debounced value (updates delay ms after the last change).


useClipboard

Copy text to clipboard with status tracking.

const { copied, error, copy } = useClipboard();

Returns:

Field Type Description
copied boolean True for 2 seconds after a successful copy
error string|null Error message if copy failed
copy (text: string) => Promise Copy function

Handles both modern Clipboard API and fallback for older browsers/HTTP.


useAsync

Manage async operations with loading, error, and stale-result prevention.

const { execute, data, loading, error, reset } = useAsync(asyncFn, { immediate: false });
Param Type Description
asyncFn () => Promise The async function to execute
options.immediate boolean Auto-execute on mount (default: false)

Returns:

Field Type Description
execute (...args) => Promise Trigger the async operation
data any Resolved value
loading boolean True while the operation is in progress
error Error|null Rejection error
reset () => void Clear data and error

Key feature: Discards stale results automatically. If you call execute twice in quick succession, only the latest result is kept.


useFileUpload

File reading with type and size validation.

const { file, fileData, error, readFile, reset } = useFileUpload(options);
Option Type Description
accept RegExp MIME type pattern (e.g., /^image\//)
maxSize number Max file size in bytes
readAs string 'dataURL', 'text', or 'arrayBuffer'

Returns:

Field Type Description
file File|null The selected File object
fileData string|ArrayBuffer|null The read file content
error string|null Validation or read error
readFile (file: File) => void Trigger file reading
reset () => void Clear all state

useKeyboardShortcut

Register keyboard shortcuts with modifier support.

useKeyboardShortcut(key, callback, options);
Param Type Description
key string Key to listen for (e.g., 's', 'Enter', 'Escape')
callback () => void Handler function
options.ctrl boolean Require Ctrl/Cmd key
options.shift boolean Require Shift key
options.alt boolean Require Alt key

Key feature: Automatically ignores keypresses when focused on input/textarea/select elements.


useInterval

setInterval with proper React lifecycle management.

useInterval(callback, delay);
Param Type Description
callback () => void Function to call on each interval
delay number|null Milliseconds between calls. Pass null to pause.

Always calls with the latest closure (no stale state). Based on the Dan Abramov pattern.


useUndo

Undo/redo state history.

const { state, setState, undo, redo, canUndo, canRedo, reset } = useUndo(initialValue);
Field Type Description
state any Current value
setState (value) => void Update value (pushes to history)
undo () => void Revert to previous value
redo () => void Re-apply undone value
canUndo boolean True if undo is available
canRedo boolean True if redo is available
reset (value) => void Clear history and set new value

Supports updater functions: setState(prev => prev + 1). History is capped at 50 entries.


useMediaQuery

Reactive CSS media query matching.

const matches = useMediaQuery(query);
Param Type Description
query string CSS media query (e.g., '(min-width: 1024px)')

Returns: boolean -- true if the query currently matches.

SSR-safe (returns false during server rendering).


useFullscreen

CSS-based fullscreen overlay with escape key handling.

const { isFullscreen, enterFullscreen, exitFullscreen, toggleFullscreen } = useFullscreen(ref);
Param Type Description
ref React.RefObject Ref to the element to fullscreen

Uses a CSS overlay approach instead of the browser Fullscreen API, avoiding cross-browser quirks. Handles Escape key and prevents body scroll.


useObjectURL

Blob URL management with automatic memory cleanup.

const [url, setBlob] = useObjectURL();
Field Type Description
url string|null The object URL for the current blob
setBlob (blob: Blob|null) => void Set a new blob (revokes the old URL)

Automatically revokes object URLs on unmount to prevent memory leaks.


Hooks That Emerged at Scale

These hooks were extracted as patterns repeated across 30+ features:

General-Purpose

Hook Purpose
useToolSettings Per-feature settings with auto-namespaced localStorage and partial update
useToolHistory Per-feature history with auto-timestamping, capping (default 50), and per-item removal
useFavorites User-favorited features persisted to localStorage
useRecentTools Recently-visited feature tracking for quick access
useStopwatch Stopwatch state machine with lap tracking, fastest/slowest detection, text/CSV export
useTimer Countdown timer state machine with presets, progress percentage, and notification support
useVersionCheck Compares deployed version against cached version for update detection

Chain System

Hook Purpose
useChainExecution Step-by-step chain state machine: select tool, run, re-run with new params, truncate
useMultiChainTabs Tab lifecycle for the chain drawer (add, remove, rename, max 5 tabs)
useUsageGraph Logs chain transitions to localStorage, computes recency-weighted suggestion scores
useSavedPipelines Named pipeline persistence (save, delete, rename, replay)

See Chaining & Pipelines for the full chain system architecture.