@supunlakmal/hooks
v1.3.1
Published
A collection of reusable React hooks
Maintainers
Keywords
Readme
@supunlakmal/hooks
A comprehensive collection of production-ready, reusable React hooks written in TypeScript to simplify common UI patterns and browser API interactions.
Stop reinventing the wheel! @supunlakmal/hooks provides a wide arrays, easy-to-use hooks covering everything from state management enhancements and side effects to browser APIs and performance optimizations.
Why choose @supunlakmal/hooks?
- 🚀 Extensive Collection: Over 60+ hooks covering a vast range of common React development needs.
- 🛡️ Type-Safe: Written entirely in TypeScript for robust development.
- ✨ Simple API: Designed for ease of use and minimal boilerplate.
- 🌍 SSR Compatible: Hooks are designed to work safely in server-side rendering environments.
- 🧹 Automatic Cleanup: Handles listeners, timers, and observers correctly.
- ⚡ Performance Focused: Includes hooks like
useDebounce,useThrottle, anduseVirtualListfor optimization. - 🧩 Minimal Dependencies: Core hooks have zero runtime dependencies (unless specified in individual hook docs).
Installation
npm install @supunlakmal/hooks
# or
yarn add @supunlakmal/hooksQuick Start Example
import React, { useState } from 'react';
import { useToggle, useDebounce, useWindowSize } from '@supunlakmal/hooks';
function ExampleComponent() {
// Effortlessly manage boolean state
const [isOpen, toggle] = useToggle(false);
// Debounce rapid input changes
const [inputValue, setInputValue] = useState('');
const debouncedSearchTerm = useDebounce(inputValue, 500);
// Get window dimensions easily
const { width, height } = useWindowSize();
// Use debounced value for API calls, etc.
React.useEffect(() => {
if (debouncedSearchTerm) {
console.log(`Searching for: ${debouncedSearchTerm}`);
// Fetch API call here...
}
}, [debouncedSearchTerm]);
return (
<div>
{/* useToggle Example */}
<button onClick={toggle}>{isOpen ? 'Close' : 'Open'}</button>
{isOpen && <p>Content is visible!</p>}
<hr />
{/* useDebounce Example */}
<input
type="text"
placeholder="Search..."
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<p>Typing: {inputValue}</p>
<p>Debounced: {debouncedSearchTerm}</p>
<hr />
{/* useWindowSize Example */}
<p>
Window Size: {width}px x {height}px
</p>
</div>
);
}Available Hooks
Hooks are organized into thematic categories so you can quickly jump to the patterns you need. Every entry links to its detailed guide in docs/.
1. State Management
Enhanced useState-style primitives for toggles, lists, finite state machines, and other complex data structures.
| Hook | Description |
| :--- | :--- |
| useBoolean | Manages a boolean state with explicit setTrue, setFalse, and toggle functions. |
| useConst | Initializes and returns a constant value that persists across renders. |
| useControlledRerenderState | A useState alternative where the state setter can cancel a re-render. |
| useCounter | Manages a number state with increment, decrement, set, and reset actions. |
| useCycle | Cycles through a predefined list of values. |
| useDefault | Returns a default value if the provided value is null or undefined. |
| useDerivedState | A semantic wrapper around useMemo for creating state based on other values. |
| useEnum | Manages state that is constrained to the values of a given enum object. |
| useFiniteStateMachine | Manages complex state using an explicit finite state machine definition. |
| useFirstMountState | Returns true only on the first render of a component. |
| useFunctionalState | A useState variant that returns a getter function for the state. |
| useHistoryState | Manages state with a history, allowing for undo and redo operations. |
| useIsFirstRender | Returns true only on the initial render of a component. |
| useIsMounted | Returns a function that indicates if the component is currently mounted. |
| useList | Manages an array state with a comprehensive set of list manipulation actions. |
| useListState | Manages an array state with basic list manipulation functions. |
| useMap | Manages a Map object as state with actions to manipulate it. |
| useMapState | Manages a key-value object as state with set, remove, and reset functions. |
| useMediatedState | A useState variant where every value set is passed through a mediator function. |
| usePrevious | Returns the value of a prop or state from the previous render. |
| usePreviousDifferent | Returns the last value that was different from the current value. |
| useQueue | Manages a queue (First-In, First-Out) with methods to add, remove, and peek. |
| useResetState | A useState variant that includes a function to reset the state to its initial value. |
| useSet | Manages a Set object as state with actions to manipulate it. |
| useSetState | Manages an object state, merging updates similarly to this.setState in class components. |
| useStateWithHistory | Manages state with a history of changes, allowing for undo and redo operations. |
| useStepper | Manages state for multi-step forms or wizards. |
| useToggle | Manages a boolean state with a toggle function. |
2. Side Effects & Lifecycle
Hooks that orchestrate effects, logging, and lifecycle nuances beyond vanilla useEffect.
| Hook | Description |
| :--- | :--- |
| useConditionalEffect | A useEffect that only runs its callback if a set of conditions are met. |
| useCustomCompareEffect | A useEffect that uses a custom comparator function for its dependency array. |
| useDeepCompareEffect | A useEffect that performs a deep comparison of its dependencies. |
| useDebouncedEffect | A useEffect whose callback function is debounced. |
| useIsomorphicLayoutEffect | A hook that uses useLayoutEffect in the browser and useEffect on the server. |
| useLifecycleLogger | Logs component lifecycle events (mount, update, unmount) to the console. |
| useLogger | Logs component lifecycle events and prop changes. |
| useMount | Runs a callback function once when the component mounts. |
| useThrottledEffect | A useEffect whose callback function is throttled. |
| useUnmount | Runs a callback function when the component unmounts. |
| useUnmountEffect | Runs an effect only when the component is unmounted. |
| useUpdateEffect | A useEffect that skips the initial render and only runs on updates. |
| useWhyDidYouUpdate | A debugging tool that logs which props changed on a component re-render. |
| useErrorBoundary | Imperative helpers for programmatically triggering and resetting React error boundaries. |
| useReducerLogger | Wraps useReducer to log every action and resulting state, aiding debugging. |
3. Data Fetching
Helpers for REST-style data loading, request cancellation, debouncing, and network-aware flows.
| Hook | Description |
| :--- | :--- |
| useAsync | Manages the state of an asynchronous function call. |
| useAsyncAbortable | An useAsync variant that provides an AbortSignal to the async function. |
| useCachedFetch | A useFetch variant with in-memory caching to avoid redundant requests. |
| useDebouncedFetch | A useFetch variant that debounces the request trigger. |
| useDelete | A specialized useFetch for making DELETE requests. |
| useFetch | A general-purpose hook for fetching data from an API. |
| useGet | A specialized useFetch for making GET requests. |
| useIdleFetch | Triggers a data fetch when the user becomes active after a period of inactivity. |
| useLocationBasedFetch | Fetches data from an API based on the user's current geolocation. |
| useMutation | Manages asynchronous operations that modify data (e.g., POST, PUT, DELETE). |
| useNetworkAwareFetch | A useFetch variant that only runs when the user is online. |
| usePatch | A specialized useFetch for making PATCH requests. |
| usePost | A specialized useFetch for making POST requests. |
| usePromise | Manages the state of a promise-based function. |
| usePut | A specialized useFetch for making PUT requests. |
4. Browser & Web APIs
Wrappers around platform APIs such as Clipboard, Storage, Battery, Permissions, and Web Workers.
| Hook | Description |
| :--- | :--- |
| useBatteryStatus | Tracks the device's battery status using the Battery Status API. |
| useBroadcastChannel | Enables cross-tab/window communication using the Broadcast Channel API. |
| useClipboard | Interacts with the system clipboard for copying and pasting. |
| useClipboardWithFeedback | An extension of useClipboard that provides feedback when text is copied. |
| useCookie | Manages a specific browser cookie. |
| useCopyToClipboard | A hook specifically for copying text to the clipboard. |
| useDeviceMotion | Tracks device motion information like acceleration and rotation rate. |
| useDeviceOrientation | Tracks the physical orientation of the device. |
| useDocumentTitle | Sets the document.title of the page. |
| useEventSource | Connects to a Server-Sent Events (SSE) endpoint. |
| useEyeDropper | Uses the experimental EyeDropper API to sample colors from the screen. |
| useFavicon | Dynamically sets the website's favicon. |
| useFullscreen | Manages the fullscreen state for a specific element. |
| useGeolocation | Tracks the user's geolocation. |
| useGeolocationContinuous | Provides a continuous stream of geolocation data. |
| useIdleCallback | Schedules a function to be executed during browser idle periods. |
| useIdleDetection | Detects user idle state and screen lock status using the Idle Detection API. |
| useLocalStorage | Manages state with localStorage, automatically syncing between state and storage. |
| useLocalStorageQueue | Manages a queue that is persisted in localStorage. |
| useLocalStorageValue | Manages a single localStorage key. |
| useMediaStream | Manages access to the user's media devices (camera, microphone). |
| useNetworkAwareWebSocket | Manages a WebSocket connection that is only active when the user is online. |
| useNetworkSpeed | Gets information about the user's network connection speed and type. |
| useNetworkState | Tracks the state of the browser's network connection. |
| useNotification | Manages web notifications. |
| useOnlineStatus | Tracks the browser's online status. |
| useOrientation | Tracks the device's screen orientation. |
| usePageVisibility | Tracks the visibility state of the browser page/tab. |
| usePermission | Queries the status of a browser permission using the Permissions API. |
| usePersistentCounter | A counter that persists its state in localStorage. |
| usePersistentToggle | A boolean state that persists in localStorage. |
| usePreferredLanguages | Retrieves the user's preferred languages from the browser. |
| usePrefersReducedMotion | Detects if the user prefers reduced motion. |
| useQueryParam | Synchronizes a state variable with a URL query parameter. |
| useScreenOrientation | Tracks the screen orientation state. |
| useScript | Dynamically loads an external script and tracks its loading state. |
| useSessionStorage | Manages state with sessionStorage, automatically syncing between state and storage. |
| useSpeechSynthesis | Utilizes the browser's Speech Synthesis API (Text-to-Speech). |
| useStorageValue | A generic hook for managing a single key in a Storage object. |
| useSyncedLocalStorage | A useLocalStorage variant that syncs its state across multiple tabs/windows. |
| useVibration | Interacts with the browser's Vibration API. |
| useWakeLock | Manages a screen wake lock to prevent the device from sleeping. |
| useWebSocket | Manages WebSocket connections. |
| useWebWorker | Runs a function in a web worker to avoid blocking the main thread. |
| useWorker | Another hook for running functions in a web worker. |
| useDarkMode | Synchronizes the UI theme with system preferences and persists overrides in localStorage. |
| useDebouncedGeolocation | Throttles high-frequency geolocation updates so downstream effects run at a manageable cadence. |
5. User Interface & DOM
DOM-centric hooks for layout measurements, interactions, viewport tracking, and accessibility patterns.
| Hook | Description |
| :--- | :--- |
| useBreakpoint | Determines the currently active responsive breakpoint. |
| useClickOutside | Detects clicks outside of a specified element. |
| useClickOutsideWithEscape | Triggers a callback on a click outside an element or on pressing the 'Escape' key. |
| useContextMenu | Manages the state for a custom context menu. |
| useDebouncedMediaQuery | A useMediaQuery variant that debounces the result. |
| useDebouncedWindowSize | A useWindowSize variant that provides debounced dimensions. |
| useDrag | Provides basic drag-and-drop event handling for an element. |
| useDraggable | Makes a DOM element draggable. |
| useElementSize | Observes an element's size and provides its width and height. |
| useFocusTrap | Traps focus within a specified container element. |
| useFocusWithinState | Tracks whether an element or any of its descendants has focus. |
| useHasBeenVisible | Tracks if an element has ever become visible in the viewport. |
| useHover | Detects whether a DOM element is being hovered over. |
| useHoverDelay | Tracks if an element has been hovered for a minimum specified duration. |
| useImageOnLoad | Tracks the loading status and dimensions of an image. |
| useInfiniteScroll | Implements infinite scrolling. |
| useIntersectionObserver | Tracks the visibility of an element within the viewport. |
| useMeasure | Tracks element dimensions using ResizeObserver. |
| useMediaQuery | Tracks the state of a CSS media query. |
| useMergeRefs | Merges multiple refs into a single callback ref. |
| useMobile | Returns whether the current viewport is mobile-sized. |
| useMousePosition | Tracks the current position of the mouse pointer. |
| usePageLeave | Triggers a callback when the user's mouse cursor leaves the viewport. |
| usePagination | Manages pagination state and controls. |
| usePinchZoom | Detects pinch-to-zoom gestures on a target element. |
| usePortal | Manages a React Portal. |
| useResizeObserver | Monitors changes to an element's size using ResizeObserver. |
| useRovingTabIndex | Implements the roving tabindex accessibility pattern. |
| useScrollLock | Locks and unlocks body scroll. |
| useScrollPosition | Tracks the scroll position of the window or a specific element. |
| useScrollSpy | Monitors scroll position to determine which element is currently active. |
| useScrollToTop | Provides a function to scroll the window to the top. |
| useSwipe | Detects swipe gestures on a target element. |
| useTextSelection | Tracks the user's text selection within the document. |
| useVirtualList | Optimizes the rendering of long lists by only rendering visible items. |
| useVisibility | Tracks whether an element is visible in the viewport. |
| useWindowSize | Tracks the browser window's dimensions. |
| useHookableRef | Combines refs with callbacks so consumers can observe element mount/unmount events. |
| useIsomorphicId | Creates a stable ID that works consistently in SSR and CSR environments. |
6. Event Handling
Utilities that simplify attaching listeners, key combos, long presses, and history changes.
| Hook | Description |
| :--- | :--- |
| useEventListener | Attaches an event listener to a target element. |
| useEventCallback | Creates a stable callback function that always calls the latest version of the provided callback. |
| useKeyCombo | Detects specific keyboard combinations (shortcuts). |
| useKeyPress | Detects when a specific key is pressed down. |
| useLongPress | Detects long press events on an element. |
| useRouteChange | Executes a callback when the browser's route changes. |
| useThrottledEventListener | Attaches an event listener with a throttled callback. |
7. Performance & Optimization
Debounce/throttle utilities, RAF helpers, and render diagnostics that keep components snappy.
| Hook | Description |
| :--- | :--- |
| useDebounce | Debounces a value, delaying its update until a specified time has passed without change. |
| useDebouncedCallback | Creates a debounced version of a callback function. |
| useDebouncedState | A useState variant where the state updates are debounced. |
| useForceUpdate | Provides a function to manually force a component to re-render. |
| useRafCallback | Schedules a callback to be executed on the next animation frame. |
| useRafState | A useState variant that updates state on the next animation frame. |
| useRenderCount | Tracks the number of times a component has rendered. |
| useRerender | Provides a function to manually trigger a re-render. |
| useThrottle | Throttles a value, ensuring it updates at most once per specified interval. |
| useThrottledCallback | Creates a throttled version of a callback function. |
| useThrottledScroll | Tracks window scroll position with throttled updates. |
| useThrottledState | A useState variant where state updates are throttled. |
| useCustomCompareMemo | Memo variant that reruns its factory only when a custom comparator reports dependency changes. |
| useSyncedRef | Keeps a mutable ref in sync with the latest value without re-rendering consumers. |
8. Forms
Form-centric hooks for managing inputs, validation, and lightweight i18n.
| Hook | Description |
| :--- | :--- |
| useForm | Manages form state, input changes, and submission handling. |
| useFormValidation | Manages form state with built-in validation and submission logic. |
| useTranslation | A basic internationalization (i18n) hook for translating form labels and messages. |
9. Timers & Intervals
Declarative abstractions over setTimeout and setInterval, including countdowns and idle timers.
| Hook | Description |
| :--- | :--- |
| useCountdown | Manages a countdown timer with start, pause, and reset controls. |
| useIdleTimer | Detects user inactivity. |
| useInterval | Sets up an interval that repeatedly calls a function. |
| useIntervalWhen | An useInterval variant that only runs when a specific condition is true. |
| useTimeout | Sets up a timeout that calls a function after a delay. |
10. Animation
Hooks powered by requestAnimationFrame for smooth motion primitives.
| Hook | Description |
| :--- | :--- |
| useAnimation | Manages a basic animation loop using requestAnimationFrame. |
| useAnimationFrame | Runs a callback function repeatedly using requestAnimationFrame. |
