Package Exports
- @supunlakmal/hooks
- @supunlakmal/hooks/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@supunlakmal/hooks) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
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 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
, anduseVirtualList
for optimization. - ๐งฉ Minimal Dependencies: Core hooks have zero runtime dependencies (unless specified in individual hook docs).
Installation
npm install @supunlakmal/hooks
# or
yarn add @supunlakmal/hooks
Quick 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
Explore the documentation for each hook to see detailed API information and usage examples:
Hook | Description |
---|---|
useAnimation |
Manages a simple time-based animation loop using requestAnimationFrame . |
useAsync |
Simplifies handling asynchronous operations (like API calls), managing loading, error, and success states. |
useAsyncAbortable |
Simplifies handling asynchronous operations that can be aborted. |
useBreakpoint |
Determines the currently active responsive breakpoint based on window width. |
useBroadcastChannel |
Enables cross-tab/window communication using the Broadcast Channel API. |
useCachedFetch |
A useFetch variant with simple in-memory caching and TTL. |
useClickOutside |
Executes a callback when a click/touch event occurs outside of a specified DOM element. |
useClipboard |
Provides functionality to interact with the system clipboard (copy/paste). |
useContextMenu |
Provides state and logic for implementing a custom context menu (right-click menu). |
useCopyToClipboard |
Provides a function to copy text to the clipboard and tracks status (uses fallback). |
useControlledRerenderState |
A hook to force a component to re-render |
useCountdown |
Manages a countdown timer with start, pause, and reset controls. |
useCounter |
A basic counter hook |
useConditionalEffect |
A useEffect variant that allows you to conditionally run the effect. |
useDarkMode |
Manages application theme preference (dark/light mode) with OS detection and local storage persistence. |
useDebouncedState |
Debounces a state, delaying updates until a certain time has passed without changes. |
useDebounce |
Debounces a value, delaying updates until a certain time has passed without changes. |
useDeepCompareEffect |
A useEffect variant that performs a deep comparison of dependencies. |
useDebouncedCallback |
Debounces a callback function, delaying its execution until a certain time has passed without changes. |
useDebouncedEffect |
A useEffect variant that debounces the effect callback. |
useDerivedState |
Computes derived state based on other values, recomputing only when dependencies change (wraps useMemo ). |
useDeviceMotion |
Tracks device motion information (acceleration, rotation rate) via the devicemotion event. |
useDeviceOrientation |
Tracks the physical orientation of the device via the deviceorientation event. |
useDrag |
Provides basic HTML Drag and Drop API event handling (dragstart , drag , dragend ) for an element. |
useConditionalEffect |
A useEffect variant that allows you to conditionally run the effect. |
useCounter |
A basic counter hook |
useGeolocationContinuous |
Tracks the user's geographic location continuously using the Geolocation API. |
useErrorBoundary |
A hook to add error boundary to a component |
useMobile |
Detects if the current viewport is mobile-sized based on a configurable breakpoint |
useNewFullscreen |
Enters and exits fullscreen mode for an element, tracking the current state. |
useDraggable |
Adds direct element draggability (positioning via transform) using pointer events, with bounds support. |
useElementSize |
Efficiently tracks the dimensions (width/height) of a DOM element using ResizeObserver . |
useFirstMountState |
Returns true if the component is rendering for the first time, false otherwise. |
useEventListener |
Robustly attaches event listeners to window , document , or elements, handling cleanup. |
useFetch |
A simple hook for fetching data, managing loading and error states. |
useFiniteStateMachine |
Manages complex component state using an explicit state machine definition. |
useFocusTrap |
Traps keyboard focus within a specified container element when active (for modals, dialogs). |
useForm |
A basic hook for managing form state, input changes, and submission. |
useFormValidation |
A comprehensive hook for form state, validation (change/blur/submit), and submission handling. |
useFullscreen |
Enters and exits fullscreen mode for an element, tracking the current state. |
useGeolocation |
Tracks the user's geographic location using the Geolocation API. |
useHover |
Tracks whether the mouse pointer is currently hovering over a specific DOM element. |
useFunctionalState |
Functional state updates for React components. |
useHookableRef |
Create a ref that can be used in a hook. |
useIsMounted |
A hook that returns true if the component is mounted. |
useIsomorphicLayoutEffect |
A useLayoutEffect variant that works on the server and the client. |
useLifecycleLogger |
A hook that logs the component's lifecycle events. |
useList |
A hook that provides functions to manipulate a list. |
useLocalStorageValue |
Get the value from local storage. |
useMeasure |
Get the size of an element |
useMediatedState |
Manages a mediated state value. |
useCustomCompareEffect |
A useEffect variant that allow to provide custom compore logic |
useCustomCompareMemo |
A useMemo variant that allow to provide custom compore logic |
usePreviousDifferent |
Tracks the previous different value of a state or prop from the last render. |
useInfiniteScroll |
Facilitates infinite scrolling using IntersectionObserver to trigger loading more data. |
useIntersectionObserver |
Monitors the intersection of a target element with the viewport or an ancestor. |
useInterval |
A declarative hook for setting intervals (setInterval ) with automatic cleanup. |
useIsFirstRender |
Returns true if the component is rendering for the first time, false otherwise. |
useKeyCombo |
Detects specific keyboard combinations (shortcuts) being pressed. |
useKeyPress |
Detects whether a specific key is currently being pressed down. |
useLocalStorage |
Manages state persisted in localStorage , synchronizing across tabs. |
useLogger |
Development utility to log component lifecycle events and prop changes. |
useLongPress |
Detects long press gestures (mouse or touch) on a target element. |
useMap |
Manages state in the form of a JavaScript Map , providing immutable update actions. |
useMediaQuery |
Tracks the state of a CSS media query (e.g., viewport size, orientation, color scheme). |
useNetworkState |
Tracks the network state. |
useMergeRefs |
Merges multiple React refs (callback or object refs) into a single callback ref. |
useMount |
Executes a callback function exactly once when the component mounts. |
useMutation |
Simplifies handling asynchronous data modification operations (POST, PUT, DELETE), managing status. |
useNetworkSpeed |
Provides information about the user's network connection (speed, type) using the Network Information API. |
usePromise |
Simplifies handling promises, managing loading, error, and success states. |
useOnlineStatus |
Tracks the browser's online/offline connection status. |
usePageVisibility |
Tracks the visibility state of the current browser tab/page using the Page Visibility API. |
useOldUpdateEffect |
A useEffect variant that skips the effect execution after the initial render (mount). |
usePagination |
Manages pagination logic for client-side data sets. |
usePermission |
Queries the status of browser permissions (geolocation, notifications, etc.) using the Permissions API. |
usePortal |
Simplifies the creation and management of React Portals. |
usePrevious |
Tracks the previous value of a state or prop from the last render. |
useQueryParam |
Synchronizes a React state variable with a URL query parameter. |
useReducerLogger |
Wraps useReducer to automatically log actions and state changes in development. |
useRenderCount |
Tracks the number of times a component has rendered. |
useRafCallback |
Creates a callback based on requestAnimationFrame. |
useResizeObserver |
Monitors changes to the dimensions of a target element using the ResizeObserver API. |
useRouteChange |
Executes a callback whenever the browser's URL path changes (handles popstate and pushState ). |
useRovingTabIndex |
Implements the roving tabindex accessibility pattern for keyboard navigation within a group. |
useScrollPosition |
Tracks the current X and Y scroll position of the window or a specified element. |
useScrollSpy |
Monitors scroll position to determine which section element is currently active in the viewport. |
useScrollToTop |
Provides a function to programmatically scroll the window to the top. |
useSessionStorage |
Manages state persisted in sessionStorage for the duration of the session. |
useSet |
Manages state in the form of a JavaScript Set , providing immutable update actions. |
useStateWithHistory |
Manages state with undo/redo history tracking. |
useRerender |
Force to re-render the component. |
useSwipe |
Detects swipe gestures (left, right, up, down) on touch-enabled devices for a specified element. |
useThrottle |
Throttles a value, ensuring updates do not occur more frequently than a specified limit. |
useStepper |
A hook to use a basic step logic. |
useStorageValue |
A hook to get the value from local or session storage. |
useThrottledState |
Throttles a state, ensuring updates do not occur more frequently than a specified limit. |
useThrottledCallback |
Throttles a callback, ensuring updates do not occur more frequently than a specified limit. |
useTimeout |
A declarative hook for setting timeouts (setTimeout ) with automatic cleanup. |
useToggle |
Manages boolean state with convenient toggle, setOn, and setOff functions. |
useTranslation |
A basic hook for handling internationalization (i18n) with static resources. |
useUnmount |
Executes a cleanup function exactly once when the component unmounts. |
useUpdateEffect |
A useEffect variant that skips the effect execution after the initial render (mount). |
useVirtualList |
Performance optimization for rendering long lists by rendering only visible items (fixed height). |
useSyncedRef |
Create a ref that syncs with another value |
useUnmountEffect |
Executes a cleanup function when the component unmounts. |
useVisibility |
Tracks whether a target element is currently visible within the viewport or an ancestor using IntersectionObserver . |
useWebSocket |
Manages WebSocket connections, state, messaging, and automatic reconnection. |
useWindowSize |
Returns the current dimensions (width and height) of the browser window. |
useWhyDidYouUpdate |
Development utility to debug component re-renders by logging changed props. |
useWakeLock |
Manages the Screen Wake Lock API to prevent the screen from sleeping. |
useWebWorker |
Runs a function in a Web Worker thread to offload heavy computations from the main thread. |
useWorker |
Offloads expensive computations or functions to a separate Web Worker thread (alternative to useWebWorker). |
Live Demo
(Coming Soon!) A live demo environment showcasing all hooks will be available here