@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 array of well-tested, 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, and useVirtualList for optimization.
- 🧩 Minimal Dependencies: Core hooks have zero runtime dependencies (unless specified in individual hook docs).
Installation
npm install @supunlakmal/hooks
yarn add @supunlakmal/hooks
Quick Start Example
import React, { useState } from 'react';
import { useToggle, useDebounce, useWindowSize } from '@supunlakmal/hooks';
function ExampleComponent() {
const [isOpen, toggle] = useToggle(false);
const [inputValue, setInputValue] = useState('');
const debouncedSearchTerm = useDebounce(inputValue, 500);
const { width, height } = useWindowSize();
React.useEffect(() => {
if (debouncedSearchTerm) {
console.log(`Searching for: ${debouncedSearchTerm}`);
}
}, [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
Explore the documentation for each hook to see detailed API information and usage examples:
Manages a simple time-based animation loop using requestAnimationFrame.
Simplifies handling asynchronous operations (like API calls), managing loading, error, and success states.
Simplifies handling asynchronous operations that can be aborted.
Determines the currently active responsive breakpoint based on window width.
Enables cross-tab/window communication using the Broadcast Channel API.
A useFetch variant with simple in-memory caching and TTL.
Executes a callback when a click/touch event occurs outside of a specified DOM element.
Provides functionality to interact with the system clipboard (copy/paste).
Provides state and logic for implementing a custom context menu (right-click menu).
Provides a function to copy text to the clipboard and tracks status (uses fallback).
A hook to force a component to re-render.
Manages a countdown timer with start, pause, and reset controls.
A basic counter hook.
A useEffect variant that allows you to conditionally run the effect.
Manages application theme preference (dark/light mode) with OS detection and local storage persistence.
Debounces a state, delaying updates until a certain time has passed without changes.
A useFetch variant that debounces the fetch call.
Tracks the user's geographic location using the Geolocation API, with debouncing.
Debounces a state, delaying updates until a certain time has passed without changes.
Debounces a value, delaying updates until a certain time has passed without changes.
A useEffect variant that performs a deep comparison of dependencies.
Debounces a callback function, delaying its execution until a certain time has passed without changes.
A useEffect variant that debounces the effect callback.
Computes derived state based on other values, recomputing only when dependencies change (wraps useMemo).
Provides a state hook with a default value that is used when the state is undefined or null.
Sets and manages the document title.
Tracks device motion information (acceleration, rotation rate) via the devicemotion event.
A fetch variant that uses the user's location for the API endpoint.
Tracks the physical orientation of the device via the deviceorientation event.
Provides basic HTML Drag and Drop API event handling (dragstart, drag, dragend) for an element.
Utilizes the EyeDropper API to select colors from the screen.
Provides basic HTML Drag and Drop API event handling (dragstart, drag, dragend) for an element.
Tracks the user's geographic location continuously using the Geolocation API.
A hook to add error boundary to a component.
Detects if the current viewport is mobile-sized based on a configurable breakpoint.
Enters and exits fullscreen mode for an element, tracking the current state.
Adds direct element draggability (positioning via transform) using pointer events, with bounds support.
Efficiently tracks the dimensions (width/height) of a DOM element using ResizeObserver.
Returns true if the component is rendering for the first time, false otherwise.
Robustly attaches event listeners to window, document, or elements, handling cleanup.
A simple hook for fetching data, managing loading and error states.
Manages complex component state using an explicit state machine definition.
Traps keyboard focus within a specified container element when active (for modals, dialogs).
A basic hook for managing form state, input changes, and submission.
A comprehensive hook for form state, validation (change/blur/submit), and submission handling.
Enters and exits fullscreen mode for an element, tracking the current state.
Tracks the user's geographic location using the Geolocation API.
Tracks whether the mouse pointer is currently hovering over a specific DOM element.
Functional state updates for React components.
Create a ref that can be used in a hook.
A hook that returns true if the component is mounted.
A useLayoutEffect variant that works on the server and the client.
A hook that logs the component's lifecycle events.
A hook that provides functions to manipulate a list.
Get the value from local storage.
Manages a queue of items persisted in local storage.
Get the value from local storage.
Get the size of an element.
Manages a mediated state value.
A useEffect variant that allow to provide custom compore logic.
A useMemo variant that allow to provide custom compore logic.
Tracks the previous different value of a state or prop from the last render.
Manages boolean state that persists in local storage.
Facilitates infinite scrolling using IntersectionObserver to trigger loading more data.
Monitors the intersection of a target element with the viewport or an ancestor.
A declarative hook for setting intervals (setInterval) with automatic cleanup.
Returns true if the component is rendering for the first time, false otherwise.
Detects specific keyboard combinations (shortcuts) being pressed.
Detects whether a specific key is currently being pressed down.
Manages state persisted in localStorage, synchronizing across tabs.
Development utility to log component lifecycle events and prop changes.
Detects long press gestures (mouse or touch) on a target element.
Manages state in the form of a JavaScript Map, providing immutable update actions.
Tracks the state of a CSS media query (e.g., viewport size, orientation, color scheme).
Tracks the network state.
Merges multiple React refs (callback or object refs) into a single callback ref.
Executes a callback function exactly once when the component mounts.
Simplifies handling asynchronous data modification operations (POST, PUT, DELETE), managing status.
Provides information about the user's network connection (speed, type) using the Network Information API.
Simplifies handling promises, managing loading, error, and success states.
A useFetch variant that automatically refetches when the network status changes from offline to online.
A useWebSocket variant that automatically reconnects when the network status changes from offline to online.
Utilizes the Notification API to display desktop notifications.
Tracks the browser's online/offline connection status.
Tracks the visibility state of the current browser tab/page using the Page Visibility API.
Tracks the screen orientation (landscape or portrait).
A useEffect variant that skips the effect execution after the initial render (mount).
Manages pagination logic for client-side data sets.
Manages a counter state that persists in local storage.
Queries the status of browser permissions (geolocation, notifications, etc.) using the Permissions API.
Simplifies the creation and management of React Portals.
Tracks the user's preference for reduced motion using the prefers-reduced-motion media query.
Tracks the previous value of a state or prop from the last render.
Synchronizes a React state variable with a URL query parameter.
Wraps useReducer to automatically log actions and state changes in development.
Tracks the number of times a component has rendered.
Creates a callback based on requestAnimationFrame.
Creates a callback based on requestAnimationFrame.
Monitors changes to the dimensions of a target element using the ResizeObserver API.
Executes a callback whenever the browser's URL path changes (handles popstate and pushState).
Implements the roving tabindex accessibility pattern for keyboard navigation within a group.
Tracks the screen orientation (angle, type) using the Screen Orientation API.
Tracks the current X and Y scroll position of the window or a specified element.
Monitors scroll position to determine which section element is currently active in the viewport.
Prevents scrolling on the body element.
Provides a function to programmatically scroll the window to the top.
Manages state persisted in sessionStorage for the duration of the session.
Manages state in the form of a JavaScript Set, providing immutable update actions.
Manages state with undo/redo history tracking.
Manages state with undo/redo history tracking.
Force to re-render the component.
Detects swipe gestures (left, right, up, down) on touch-enabled devices for a specified element.
Throttles a value, ensuring updates do not occur more frequently than a specified limit.
A hook to use a basic step logic.
A hook to get the value from local or session storage.
A hook to get the value from local or session storage.
Throttles a state, ensuring updates do not occur more frequently than a specified limit.
Throttles a callback, ensuring updates do not occur more frequently than a specified limit.
Attaches an event listener and throttles the callback execution.
A declarative hook for setting timeouts (setTimeout) with automatic cleanup.
Manages boolean state with convenient toggle, setOn, and setOff functions.
A basic hook for handling internationalization (i18n) with static resources.
Executes a cleanup function exactly once when the component unmounts.
A useEffect variant that skips the effect execution after the initial render (mount).
Performance optimization for rendering long lists by rendering only visible items (fixed height).
Utilizes the Vibration API to trigger device vibrations.
Performance optimization for rendering long lists by rendering only visible items (fixed height).
Create a ref that syncs with another value.
Executes a cleanup function when the component unmounts.
Tracks whether a target element is currently visible within the viewport or an ancestor using IntersectionObserver.
Manages WebSocket connections, state, messaging, and automatic reconnection.
Returns the current dimensions (width and height) of the browser window.
Development utility to debug component re-renders by logging changed props.
Monitors user activity and triggers callbacks based on idle/active status.
Manages the Screen Wake Lock API to prevent the screen from sleeping.
Runs a function in a Web Worker thread to offload heavy computations from the main thread.
Offloads expensive computations or functions to a separate Web Worker thread (alternative to useWebWorker).
Live Demo
A live demo environment showcasing all hooks will be available here