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
| Hook | Purpose |
|---|---|
useClickOutside | Fire a callback when a click lands outside a ref. |
useCopy | Copy text to the clipboard, with copied / failed flags that reset. |
useDebounce | Debounce a rapidly-changing value. |
useLocalStorage | State synced to localStorage. |
useMediaQuery | Track a CSS media query. |
useIsMobile | true below the mobile breakpoint. |
usePrevious | The value from the previous render. |
useToggle | Boolean state with toggle/set helpers. |
useHasMounted | false 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.