Skip to main content

Hooks

@rtorcato/react-common ships a set of small, headless React hooks — no UI, no extra dependencies. Import them from the package root:

import { usePrevious, useToggle } from '@rtorcato/react-common'

Available hooks​

HookPurpose
useClickOutsideFire a callback when a click lands outside a ref.
useCopyCopy text to the clipboard, with copied / failed flags that reset.
useDebounceDebounce a rapidly-changing value.
useLocalStorageState synced to localStorage.
useMediaQueryTrack a CSS media query.
useIsMobiletrue below the mobile breakpoint.
usePreviousThe value from the previous render.
useToggleBoolean state with toggle/set helpers.
useHasMountedfalse until the component has mounted on the client.

useCopy​

useCopy(timeout?: number): { copy: (text: string) => Promise<boolean>; copied: boolean; failed: boolean }

copy(text) writes text to the clipboard. copied turns true when the copy succeeds and goes back to false after timeout milliseconds (default 2000). Copying again before then restarts the timer.

function CopyButton({ text }: { text: string }) {
const { copy, copied } = useCopy()
return <button onClick={() => copy(text)}>{copied ? 'Copied' : 'Copy'}</button>
}

copy() resolves to true on success. It resolves to false, copied stays false and failed turns true, when the browser rejects the write or has no Clipboard API. failed also resets after timeout, and the two flags are never both true. Most browsers only allow clipboard writes on HTTPS and from a user gesture such as a click, so call copy() from an event handler. For a ready-made button, see Copy button.

const ok = await copy(text)
if (!ok) alert('Copy failed. Select the text and copy it by hand.')

useHasMounted​

false on the server and the first client render, true after mount. Defer browser-only values with it so the first client render matches the server HTML.

function ThemeLabel() {
const mounted = useHasMounted()
const { theme } = useTheme()
return <span>{mounted ? theme : null}</span>
}

usePrevious​

Returns the value usePrevious saw on the previous render, undefined on the first render only. It tracks renders, not changes: if the component re-renders while count stays the same, prev equals count.

function Counter({ count }: { count: number }) {
const prev = usePrevious(count)
return <span>Now {count}, was {prev ?? '—'}</span>
}

useToggle​

Boolean state with stable toggle / setOn / setOff helpers — the common open/closed, on/off pattern.

function Panel() {
const { value: isOpen, toggle, setOff } = useToggle()
return (
<>
<button onClick={() => toggle()}>Toggle</button>
{isOpen && <div onMouseLeave={setOff}>Content</div>}
</>
)
}

toggle() flips the value; toggle(true) / toggle(false) set it explicitly.