reactilities
v0.7.0
Published
A comprehensive collection of useful React hooks and utilities for modern web development
Maintainers
Readme
Reactilities
A comprehensive collection of useful React hooks and utilities for modern web development. Built with TypeScript for excellent developer experience and type safety.
Installation
npm install reactilities
# or
yarn add reactilities
# or
pnpm add reactilitiesRequirements
- React >= 18.0.0 (tested against React 18 and 19)
- React DOM >= 18.0.0
Note: This library uses
useSyncExternalStore, which requires React 18 or higher.
Importing
Import everything from the package root, or a single hook from its subpath — both tree-shake to only the code you use:
import { useDebounce, useLocalStorage } from 'reactilities';
// or, per-hook subpath (ships ~0.5 KB for one hook):
import { useDebounce } from 'reactilities/useDebounce';Next.js / React Server Components
Every hook ships with the "use client" directive, so you can import them from
Client Components in the Next.js App Router without any wrapper. Hooks that read
browser-only state (useMediaQuery, useLocalStorage, useSessionStorage,
useNetworkState, useDarkMode, useWindowSize, …) are built on
useSyncExternalStore and return a stable server snapshot during SSR, so they
never crash server rendering and produce no hydration mismatch — the real value
applies after mount.
Features
- 70+ React Hooks — DOM manipulation, state management, async, timers, and more
- Lifecycle Helpers — class component lifecycle methods as hooks
- Helper Functions — utility functions for common tasks
- TypeScript Types — utility types for better type safety
- TypeScript First — full type support with excellent IntelliSense; verified with
publintandare-the-types-wrong(works underbundler,node16, andnodenext) - Well Tested — 857 tests on a React 18 + 19 CI matrix
- Tree Shakable — package-root or per-hook subpath imports
- Zero Dependencies — no external dependencies except React
- SSR Safe — built for the Next.js App Router; browser-backed hooks return server snapshots instead of throwing
- Comprehensive Docs — each hook has its own detailed README
API Reference
Each hook and utility has its own detailed documentation with examples. Click on any item below to see full documentation.
DOM Hooks
Hooks for DOM manipulation and browser APIs.
- useBattery - Monitor device battery status via the Battery Status API
- useClickOutside - Detect clicks outside an element
- useDarkMode - Dark mode with system preference detection and persistence
- useDocumentTitle - Dynamically update the document title
- useEventListener - Add event listeners with automatic cleanup
- useFavicon - Dynamically update the website favicon
- useFocusTrap - Trap keyboard focus within a container (modals, drawers)
- useFullscreen - Enter, exit, and track fullscreen state on any element
- useHover - Detect hover state on any element
- useLockBodyScroll - Prevent body scrolling (for modals/overlays)
- useLongPress - Detect long press / hold on any element
- useMediaQuery - Responsive design with CSS media queries
- useMousePosition - Track real-time cursor position
- useOrientation - Track device screen orientation (portrait/landscape)
- usePageVisibility - Detect when browser tab is hidden or visible
- usePortal - Create a DOM portal container appended to document.body
- useResizeObserver - Observe element size changes with ResizeObserver
- useRovingTabIndex - Keyboard-navigable lists and menus with roving tabIndex (ARIA)
- useScrollPosition - Track window scroll position
- useScrollTo - Programmatic scroll control (top, bottom, element, or position)
- useWindowSize - Track browser window dimensions
State Hooks
Hooks for state management and persistence.
- useBoolean - Boolean state with named setTrue/setFalse/toggle controls
- useClipboard - Read from and write to the clipboard with hasCopied tracking
- useCookie - Read and write browser cookies
- useCopyToClipboard - Copy text to clipboard with fallback
- useCounter - Numeric counter with min/max bounds and step
- useList - Manage array state with push, remove, sort, and more
- useLocalStorage - Persist state in localStorage with sync
- useMap - Manage Map state with React integration
- useObjectState - Manage object state with partial updates
- usePrevious - Access the previous render's value
- useSessionStorage - Persist state in sessionStorage
- useSet - Manage Set state with React integration
- useStep - Multi-step wizard and onboarding flow state management
- useToggle - Toggle boolean state with flexible API
- useUndoRedo - State with full undo/redo history
Utility Hooks
Performance and utility hooks for common patterns.
- useAsync - Manage async operations with loading/error/success states
- useAutoSave - Auto-save data after a debounce delay with pending/saved/error status
- useCountdown - Countdown and count-up timer with controls
- useDebounce - Debounce rapidly changing values
- useDebounceCallback - Debounce a callback function (vs useDebounce which debounces values)
- useDragAndDrop - File drag-and-drop with type, count, and size validation
- useEventSource - Manage Server-Sent Events (SSE) connections
- useFetch - Data fetching with automatic abort support
- useFileReader - Read File objects as text, data URL, or ArrayBuffer
- useGeolocation - Access user's geolocation
- useIdleTimeout - Detect user inactivity after a configurable timeout
- useImageLazyLoad - Lazy-load images when they enter the viewport
- useInfiniteScroll - Infinite scroll via IntersectionObserver
- useIntersectionObserver - Detect element visibility (lazy loading, infinite scroll)
- useInterval - Run a callback on a fixed interval
- useIsMounted - Guard async state updates against unmounted components
- useKeyboardShortcuts - Handle keyboard shortcuts
- useLogger - Log component mount, update, and unmount events (dev only)
- useManualUpdate - Manually trigger a component re-render
- useNetworkState - Monitor network connectivity
- usePermission - Query browser permission status reactively
- useSpeechRecognition - Voice input via the Web Speech Recognition API
- useSpeechSynthesis - Text-to-speech via the Web Speech Synthesis API
- useThrottle - Throttle rapidly changing values
- useThrottleCallback - Throttle a callback function (vs useThrottle which throttles values)
- useTimeout - Run a callback after a delay with reset/clear
- useVirtualization - Virtualize large lists for performance
- useWebSocket - Manage WebSocket connections
- useWhyDidYouRender - Debug unnecessary re-renders by logging what changed (dev only)
- useWorker - Run heavy computations in a Web Worker off the main thread
Lifecycle Hooks
Class component lifecycle methods as hooks.
- componentDidMount - Run function after component mounts
- componentDidUpdate - Run function after every render
- componentWillMount - Run function before first render
- componentWillUnmount - Run cleanup before unmount
- useIsomorphicLayoutEffect - SSR-safe drop-in for useLayoutEffect
- useUpdateEffect - useEffect that skips the first render
Helper Functions
Utility functions for common tasks.
- classnames - Conditionally join CSS class names
- loadScript - Dynamically load external scripts
TypeScript Types
Utility types for better type safety.
Nullable<T>- Makes a type nullable (T | null)Maybe<T>- Makes a type nullable and undefined (T | null | undefined)ValueOf<T>- Extracts all possible values from an object typeDeepPartial<T>- Makes all properties optional recursivelyVoidFunction<T>- Type for void-returning functions with typed parameters
Quick Start
import {
useLocalStorage,
useDebounce,
useWindowSize,
useFetch,
useUndoRedo,
useInfiniteScroll,
classnames
} from 'reactilities';
function App() {
// Persist theme preference
const [theme, setTheme] = useLocalStorage('theme', 'light');
// Responsive layout
const { width } = useWindowSize();
const isMobile = width > 0 && width < 768;
// Debounce search input
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 300);
// Fetch with loading state
const { data, loading } = useFetch<User[]>(
`/api/users?q=${debouncedSearch}`
);
const buttonClass = classnames('btn', {
'btn-primary': theme === 'light',
'btn-dark': theme === 'dark',
'btn-sm': isMobile,
});
return (
<div>
<button className={buttonClass} onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Search..."
/>
{loading ? <Spinner /> : <UserList users={data ?? []} />}
</div>
);
}TypeScript Support
All hooks and utilities are written in TypeScript with full type definitions:
// Type inference works automatically
const [user, setUser] = useLocalStorage('user', { name: 'John', age: 30 });
// user is typed as { name: string; age: number }
// Generic types are supported
const debouncedValue = useDebounce<string>('hello', 300);
const throttledValue = useThrottle<number>(scrollY, 100);
// Async hooks are fully typed
const { data } = useFetch<User[]>('/api/users');
// data is User[] | null
// Utility types
type User = { id: string; name: string; email: string };
type NullableUser = Nullable<User>; // User | null
type MaybeUser = Maybe<User>; // User | null | undefined
type PartialUser = DeepPartial<User>; // All properties optional recursivelyTesting
Reactilities comes with comprehensive tests:
- 857 tests covering all functionality
- Run on every commit against React 18 and React 19 (CI matrix)
- Tested with Vitest and React Testing Library
License
MIT © Petar Basic
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Changelog
See CHANGELOG.md for the full version history. Notable changes are kept there following Keep a Changelog.
Support
If you find this library useful and are feeling generous, consider donating to Svratište — a day center in Belgrade providing support, meals, and shelter for people experiencing homelessness.
Made with ❤️ by Petar Basic
