JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 15
  • Score
    100M100P100Q43957F
  • License ISC

A collection of reusable React hooks

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

NPM Version License: ISC TypeScript npm GitHub last commit bundle size Install Size

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, and useVirtualList 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

useAnimationFrame

Executes a callback function on each frame of the requestAnimationFrame loop.


useBatteryStatus

Provides real-time information about the device's battery status.


useBoolean

Manages a boolean state with convenient toggle, setTrue, and setFalse functions.


useCachedFetch

A useFetch variant with simple in-memory caching and TTL.


useClickOutsideWithEscape

Triggers a callback when clicking outside an element or pressing the Escape key.


useClipboardWithFeedback

Copies text to the clipboard and shows timed feedback on success.


useConst

Initializes and returns a value that remains constant throughout the component's lifecycle.


useCookie

Provides an interface for reading, writing, and deleting cookies.


useCountdown

Manages a countdown timer with start, pause, and reset controls.


useCounter

A basic counter hook with increment, decrement, and reset functions.


useConditionalEffect

A useEffect variant that allows you to conditionally run the effect based on a boolean flag.


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.


useCycle

Cycles through a list of values with next/previous controls.


useDarkMode

Manages application theme preference (dark/light mode) with OS detection and local storage persistence.


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.


useDebouncedFetch

A useFetch variant that debounces the fetch call.


useDebouncedGeolocation

Tracks the user's geographic location using the Geolocation API, with debouncing.


useDebouncedMediaQuery

Debounces the result of a CSS media query.


useDebouncedWindowSize

Provides window dimensions debounced by a specified delay.


useDefault

Provides a default value if the input value is null or undefined.


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.


useDocumentTitle

Sets and manages the document title.


useDraggable

Adds direct element draggability (positioning via transform) using pointer events, with bounds support.


useDrag

Provides basic HTML Drag and Drop API event handling (dragstart, drag, dragend) for an element.


useElementSize

Efficiently tracks the dimensions (width/height) of a DOM element using ResizeObserver.


useEnum

A hook to manage a state that cycles through values of an enum. (Description inferred - doc file was blank).


useErrorBoundary

A hook to add error boundary to a component.


useEventCallback

Creates a stable function reference that always calls the latest version of a callback.


useEventListener

Robustly attaches event listeners to window, document, or elements, handling cleanup.


useEventSource

Manages a connection to a Server-Sent Events (SSE) endpoint.


useEyeDropper

Utilizes the EyeDropper API to select colors from the screen.


useFavicon

Dynamically sets the website's favicon.


useFetch

A simple hook for fetching data, managing loading and error states.


useFiniteStateMachine

Manages complex component state using an explicit state machine definition.


useFirstMountState

Returns true if the component is rendering for the first time, false otherwise.


useFocusTrap

Traps keyboard focus within a specified container element when active (for modals, dialogs).


useFocusWithinState

Determines if a specified element or any of its descendants currently have focus.


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.


useForceUpdate

A hook to force a component to re-render.


useFullscreen

Enters and exits fullscreen mode for an element, tracking the current state.


useFunctionalState

Functional state updates for React components. (Description inferred - doc file was blank).


useGeolocation

Tracks the user's geographic location using the Geolocation API.


useGeolocationContinuous

Tracks the user's geographic location continuously using the Geolocation API.


useHasBeenVisible

Determines if an element has ever been visible within the viewport.


useHistoryState

Manages state with undo/redo history tracking.


useHookableRef

Create a ref that can be used in a hook. (Description inferred - doc file was blank).


useHover

Tracks whether the mouse pointer is currently hovering over a specific DOM element.


useHoverDelay

Tracks hover state with a minimum duration delay.


useIdleCallback

Schedules a function to be called during browser idle periods using requestIdleCallback.


useIdleDetection

Monitors user idle state and screen lock status using the experimental Idle Detection API.


useIdleFetch

Initiates a data fetch after the user becomes active following a period of inactivity.


useIdleTimer

Monitors user activity and triggers callbacks based on idle/active status.


useImageOnLoad

Tracks the loading status and dimensions of an image element.


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.


useIntervalWhen

Sets up an interval that only runs when a specific condition is met.


useIsFirstRender

Returns true if the component is rendering for the first time, false otherwise.


useIsMobile

Detects if the current viewport is mobile-sized based on a configurable breakpoint.


useIsMounted

A hook that returns true if the component is mounted.


useIsomorphicId

Generates unique IDs that are stable across server and client rendering environments.


useIsomorphicLayoutEffect

A useLayoutEffect variant that works on the server and the client.


useKeyCombo

Detects specific keyboard combinations (shortcuts) being pressed.


useKeyPress

Detects whether a specific key is currently being pressed down.


useLifecycleLogger

A hook that logs the component's lifecycle events.


useList

A hook that provides functions to manipulate a list.


useListState

Manages an array state with helper functions for common array operations.


useLocalStorage

Manages state persisted in localStorage, synchronizing across tabs.


useLocalStorageQueue

Manages a queue of items persisted in local storage.


useLocalStorageValue

Get the value from local storage.


useLogger

Development utility to log component lifecycle events and prop changes.


useLongPress

Detects long press gestures (mouse or touch) on a target element.


useLocationBasedFetch

A fetch variant that uses the user's location for the API endpoint.


useMap

Manages state in the form of a JavaScript Map, providing immutable update actions.


useMapState

Manages an object or a Map-like state with helper functions to set, remove, and reset key-value pairs.


useMeasure

Get the size of an element. (Description inferred - doc file was blank).


useMediaStream

Simplifies requesting and managing access to the user's camera and/or microphone.


useMediatedState

Manages a mediated state value.


useMediaQuery

Tracks the state of a CSS media query.


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.


useMousePosition

Tracks the current position of the mouse pointer globally.


useMutation

Simplifies handling asynchronous data modification operations (POST, PUT, DELETE), managing status.


useNetworkAwareFetch

A useFetch variant that automatically refetches when the network status changes from offline to online.


useNetworkAwareWebSocket

A useWebSocket variant that automatically reconnects when the network status changes from offline to online.


useNetworkSpeed

Provides information about the user's network connection (speed, type) using the Network Information API.


useNetworkState

Tracks the network state.


useNewFullscreen

Enters and exits fullscreen mode for an element, tracking the current state. (Description inferred - doc was same as useFullscreen)


useNotification

Utilizes the Notification API to display desktop notifications.


useOnlineStatus

Tracks the browser's online/offline connection status.


useOrientation

Tracks the screen orientation (landscape or portrait).


usePageLeave

Triggers a callback function when the user's mouse cursor leaves the main browser window or document area.


usePageVisibility

Tracks the visibility state of the current browser tab/page using the Page Visibility API.


usePagination

Manages pagination logic for client-side data sets.


usePermission

Queries the status of browser permissions (geolocation, notifications, etc.) using the Permissions API.


usePersistentCounter

Manages a counter state that persists in local storage.


usePersistentToggle

Manages boolean state that persists in local storage.


usePinchZoom

Detects and reacts to pinch-to-zoom gestures on a specified element.


usePortal

Simplifies the creation and management of React Portals.


usePrefersReducedMotion

Tracks the user's preference for reduced motion using the prefers-reduced-motion media query.


usePreferredLanguages

Returns an array of the user's preferred languages, as configured in their browser.


usePrevious

Tracks the previous value of a state or prop from the last render.


usePreviousDifferent

Tracks the previous different value of a state or prop from the last render.


usePromise

Simplifies handling promises, managing loading, error, and success states.


useQueue

Manages a stateful queue (First-In, First-Out).


useRafCallback

Creates a callback based on requestAnimationFrame.


useRafState

Manages state updates deferred to the next browser animation frame.


useReducerLogger

Wraps useReducer to automatically log actions and state changes in development.


useRenderCount

Tracks the number of times a component has rendered.


useRerender

Force to re-render the component.


useResetState

Provides a state variable and a function to reset it to its initial value.


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.


useScreenOrientation

Tracks the screen orientation (angle, type) using the Screen Orientation API.


useScript

Dynamically loads an external JavaScript script and tracks its loading status.


useScrollLock

Prevents scrolling on the body element.


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.


useSetState

Manages object state allowing partial updates, similar to class component setState.


useStepper

A hook to use a basic step logic.


useStorageValue

A hook to get the value from local or session storage.


useSwipe

Detects swipe gestures (left, right, up, down) on touch-enabled devices for a specified element.


useSyncedLocalStorage

Manages state persisted in localStorage and synchronizes across tabs.


useSyncedRef

Create a ref that syncs with another value.


useTextSelection

Tracks the text currently selected by the user within the document.


useThrottle

Throttles a value, delaying updates until a certain time has passed without changes.


useThrottledCallback

Throttles a callback, ensuring updates do not occur more frequently than a specified limit.


useThrottledEventListener

Attaches an event listener and throttles the callback execution.


useThrottledScroll

Tracks the window's scroll position with throttled updates.


useThrottledState

Throttles a state, 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.


useUnmountEffect

Executes a cleanup function when the component unmounts.


useUpdateEffect

A useEffect variant that skips the effect execution after the initial render (mount).


useVibration

Utilizes the Vibration API to trigger device vibrations.


useVirtualList

Performance optimization for rendering long lists by rendering only visible items (fixed height).


useVisibility

Tracks whether a target element is currently visible within the viewport or an ancestor using IntersectionObserver.


useWakeLock

Manages the Screen Wake Lock API to prevent the screen from sleeping.


useWebSocket

Manages WebSocket connections, state, messaging, and automatic reconnection.


useWebWorker

Runs a function in a Web Worker thread to offload heavy computations from the main thread.


useWhyDidYouUpdate

Development utility to debug component re-renders by logging changed props.


useWindowSize

Returns the current dimensions (width and height) of the browser window.


useWorker

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