@sonardigital/hooks
v1.1.4
Published
Reusable, type-safe React hooks used across Sonar Digital projects. Small, focused utilities with sensible APIs and first-class TypeScript support.
Readme
@sonardigital/hooks
Reusable, type-safe React hooks used across Sonar Digital projects. Small, focused utilities with sensible APIs and first-class TypeScript support.
Features
- Typed: Strong TypeScript types out of the box
- Focused: A handful of well-tested, practical hooks
- Lightweight: Minimal footprint and simple APIs
Installation
npm install @sonardigital/hooksyarn add @sonardigital/hookspnpm add @sonardigital/hooksQuick start
import { useDebounce, useScrollToTop, useStopwatch, useTimeout, useBrowserPageTitle } from '@sonardigital/hooks';
function Example({ search }: { search: string }) {
const debounced = useDebounce(search, 400);
useBrowserPageTitle(`Searching: ${debounced || 'Idle'}`);
return null;
}API Reference
useDebounce
Debounce any changing value and optionally run a callback when the debounced value updates.
const debouncedValue = useDebounce<T>(value: T, delay?: number, callback?: (v: T) => void): T- value: value to debounce
- delay: milliseconds to wait (default: 500)
- callback: called with the latest debounced value after the delay
Example:
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 300, (v) => {
// fire search with v
});useScrollToTop
Scrolls the window to the top whenever the provided dependencies change.
useScrollToTop({ deps?: React.DependencyList })Example with React Router:
import { useLocation } from 'react-router-dom';
const { pathname } = useLocation();
useScrollToTop({ deps: [pathname] });useStopwatch
Simple stopwatch that counts time elapsed since a given date (or now if omitted).
const { time, days, hours, minutes, seconds } = useStopwatch(date?: string)- time:
{ days, hours, minutes, seconds, raw } - days/hours/minutes/seconds: zero-padded strings for display
Example:
const { days, hours, minutes, seconds } = useStopwatch('2024-01-01T00:00:00Z');useTimeout
Countdown timer to a target dayjs date. Updates every second.
const { timeLeft } = useTimeout({ date: Dayjs })- timeLeft:
{ days, hours, minutes, seconds, expired }
Example:
import dayjs from 'dayjs';
const { timeLeft } = useTimeout({ date: dayjs().add(10, 'minute') });useBrowserPageTitle
Sets the browser tab title while the component is mounted and restores the previous title on unmount.
useBrowserPageTitle(title: string)TypeScript
All hooks are fully typed. Generics are inferred where appropriate (e.g., useDebounce<T>).
Requirements
- React 18+
- TypeScript 5+
Development
npm install
npm run lint
npm run format
npm run precommitLicense
ISC
Credits
dayjsfor time utilities used byuseStopwatchanduseTimeout
