šŸŽ© You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP →
Sign In

@supunlakmal/hooks

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@supunlakmal/hooks

A collection of reusable React hooks

latest
Source
npmnpm
Version
1.3.1
Version published
Weekly downloads
265
28.02%
Maintainers
1
Weekly downloads
Ā 
Created
Source

@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

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.

HookDescription
useBooleanManages a boolean state with explicit setTrue, setFalse, and toggle functions.
useConstInitializes and returns a constant value that persists across renders.
useControlledRerenderStateA useState alternative where the state setter can cancel a re-render.
useCounterManages a number state with increment, decrement, set, and reset actions.
useCycleCycles through a predefined list of values.
useDefaultReturns a default value if the provided value is null or undefined.
useDerivedStateA semantic wrapper around useMemo for creating state based on other values.
useEnumManages state that is constrained to the values of a given enum object.
useFiniteStateMachineManages complex state using an explicit finite state machine definition.
useFirstMountStateReturns true only on the first render of a component.
useFunctionalStateA useState variant that returns a getter function for the state.
useHistoryStateManages state with a history, allowing for undo and redo operations.
useIsFirstRenderReturns true only on the initial render of a component.
useIsMountedReturns a function that indicates if the component is currently mounted.
useListManages an array state with a comprehensive set of list manipulation actions.
useListStateManages an array state with basic list manipulation functions.
useMapManages a Map object as state with actions to manipulate it.
useMapStateManages a key-value object as state with set, remove, and reset functions.
useMediatedStateA useState variant where every value set is passed through a mediator function.
usePreviousReturns the value of a prop or state from the previous render.
usePreviousDifferentReturns the last value that was different from the current value.
useQueueManages a queue (First-In, First-Out) with methods to add, remove, and peek.
useResetStateA useState variant that includes a function to reset the state to its initial value.
useSetManages a Set object as state with actions to manipulate it.
useSetStateManages an object state, merging updates similarly to this.setState in class components.
useStateWithHistoryManages state with a history of changes, allowing for undo and redo operations.
useStepperManages state for multi-step forms or wizards.
useToggleManages a boolean state with a toggle function.

2. Side Effects & Lifecycle

Hooks that orchestrate effects, logging, and lifecycle nuances beyond vanilla useEffect.

HookDescription
useConditionalEffectA useEffect that only runs its callback if a set of conditions are met.
useCustomCompareEffectA useEffect that uses a custom comparator function for its dependency array.
useDeepCompareEffectA useEffect that performs a deep comparison of its dependencies.
useDebouncedEffectA useEffect whose callback function is debounced.
useIsomorphicLayoutEffectA hook that uses useLayoutEffect in the browser and useEffect on the server.
useLifecycleLoggerLogs component lifecycle events (mount, update, unmount) to the console.
useLoggerLogs component lifecycle events and prop changes.
useMountRuns a callback function once when the component mounts.
useThrottledEffectA useEffect whose callback function is throttled.
useUnmountRuns a callback function when the component unmounts.
useUnmountEffectRuns an effect only when the component is unmounted.
useUpdateEffectA useEffect that skips the initial render and only runs on updates.
useWhyDidYouUpdateA debugging tool that logs which props changed on a component re-render.
useErrorBoundaryImperative helpers for programmatically triggering and resetting React error boundaries.
useReducerLoggerWraps 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.

HookDescription
useAsyncManages the state of an asynchronous function call.
useAsyncAbortableAn useAsync variant that provides an AbortSignal to the async function.
useCachedFetchA useFetch variant with in-memory caching to avoid redundant requests.
useDebouncedFetchA useFetch variant that debounces the request trigger.
useDeleteA specialized useFetch for making DELETE requests.
useFetchA general-purpose hook for fetching data from an API.
useGetA specialized useFetch for making GET requests.
useIdleFetchTriggers a data fetch when the user becomes active after a period of inactivity.
useLocationBasedFetchFetches data from an API based on the user's current geolocation.
useMutationManages asynchronous operations that modify data (e.g., POST, PUT, DELETE).
useNetworkAwareFetchA useFetch variant that only runs when the user is online.
usePatchA specialized useFetch for making PATCH requests.
usePostA specialized useFetch for making POST requests.
usePromiseManages the state of a promise-based function.
usePutA specialized useFetch for making PUT requests.

4. Browser & Web APIs

Wrappers around platform APIs such as Clipboard, Storage, Battery, Permissions, and Web Workers.

HookDescription
useBatteryStatusTracks the device's battery status using the Battery Status API.
useBroadcastChannelEnables cross-tab/window communication using the Broadcast Channel API.
useClipboardInteracts with the system clipboard for copying and pasting.
useClipboardWithFeedbackAn extension of useClipboard that provides feedback when text is copied.
useCookieManages a specific browser cookie.
useCopyToClipboardA hook specifically for copying text to the clipboard.
useDeviceMotionTracks device motion information like acceleration and rotation rate.
useDeviceOrientationTracks the physical orientation of the device.
useDocumentTitleSets the document.title of the page.
useEventSourceConnects to a Server-Sent Events (SSE) endpoint.
useEyeDropperUses the experimental EyeDropper API to sample colors from the screen.
useFaviconDynamically sets the website's favicon.
useFullscreenManages the fullscreen state for a specific element.
useGeolocationTracks the user's geolocation.
useGeolocationContinuousProvides a continuous stream of geolocation data.
useIdleCallbackSchedules a function to be executed during browser idle periods.
useIdleDetectionDetects user idle state and screen lock status using the Idle Detection API.
useLocalStorageManages state with localStorage, automatically syncing between state and storage.
useLocalStorageQueueManages a queue that is persisted in localStorage.
useLocalStorageValueManages a single localStorage key.
useMediaStreamManages access to the user's media devices (camera, microphone).
useNetworkAwareWebSocketManages a WebSocket connection that is only active when the user is online.
useNetworkSpeedGets information about the user's network connection speed and type.
useNetworkStateTracks the state of the browser's network connection.
useNotificationManages web notifications.
useOnlineStatusTracks the browser's online status.
useOrientationTracks the device's screen orientation.
usePageVisibilityTracks the visibility state of the browser page/tab.
usePermissionQueries the status of a browser permission using the Permissions API.
usePersistentCounterA counter that persists its state in localStorage.
usePersistentToggleA boolean state that persists in localStorage.
usePreferredLanguagesRetrieves the user's preferred languages from the browser.
usePrefersReducedMotionDetects if the user prefers reduced motion.
useQueryParamSynchronizes a state variable with a URL query parameter.
useScreenOrientationTracks the screen orientation state.
useScriptDynamically loads an external script and tracks its loading state.
useSessionStorageManages state with sessionStorage, automatically syncing between state and storage.
useSpeechSynthesisUtilizes the browser's Speech Synthesis API (Text-to-Speech).
useStorageValueA generic hook for managing a single key in a Storage object.
useSyncedLocalStorageA useLocalStorage variant that syncs its state across multiple tabs/windows.
useVibrationInteracts with the browser's Vibration API.
useWakeLockManages a screen wake lock to prevent the device from sleeping.
useWebSocketManages WebSocket connections.
useWebWorkerRuns a function in a web worker to avoid blocking the main thread.
useWorkerAnother hook for running functions in a web worker.
useDarkModeSynchronizes the UI theme with system preferences and persists overrides in localStorage.
useDebouncedGeolocationThrottles 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.

HookDescription
useBreakpointDetermines the currently active responsive breakpoint.
useClickOutsideDetects clicks outside of a specified element.
useClickOutsideWithEscapeTriggers a callback on a click outside an element or on pressing the 'Escape' key.
useContextMenuManages the state for a custom context menu.
useDebouncedMediaQueryA useMediaQuery variant that debounces the result.
useDebouncedWindowSizeA useWindowSize variant that provides debounced dimensions.
useDragProvides basic drag-and-drop event handling for an element.
useDraggableMakes a DOM element draggable.
useElementSizeObserves an element's size and provides its width and height.
useFocusTrapTraps focus within a specified container element.
useFocusWithinStateTracks whether an element or any of its descendants has focus.
useHasBeenVisibleTracks if an element has ever become visible in the viewport.
useHoverDetects whether a DOM element is being hovered over.
useHoverDelayTracks if an element has been hovered for a minimum specified duration.
useImageOnLoadTracks the loading status and dimensions of an image.
useInfiniteScrollImplements infinite scrolling.
useIntersectionObserverTracks the visibility of an element within the viewport.
useMeasureTracks element dimensions using ResizeObserver.
useMediaQueryTracks the state of a CSS media query.
useMergeRefsMerges multiple refs into a single callback ref.
useMobileReturns whether the current viewport is mobile-sized.
useMousePositionTracks the current position of the mouse pointer.
usePageLeaveTriggers a callback when the user's mouse cursor leaves the viewport.
usePaginationManages pagination state and controls.
usePinchZoomDetects pinch-to-zoom gestures on a target element.
usePortalManages a React Portal.
useResizeObserverMonitors changes to an element's size using ResizeObserver.
useRovingTabIndexImplements the roving tabindex accessibility pattern.
useScrollLockLocks and unlocks body scroll.
useScrollPositionTracks the scroll position of the window or a specific element.
useScrollSpyMonitors scroll position to determine which element is currently active.
useScrollToTopProvides a function to scroll the window to the top.
useSwipeDetects swipe gestures on a target element.
useTextSelectionTracks the user's text selection within the document.
useVirtualListOptimizes the rendering of long lists by only rendering visible items.
useVisibilityTracks whether an element is visible in the viewport.
useWindowSizeTracks the browser window's dimensions.
useHookableRefCombines refs with callbacks so consumers can observe element mount/unmount events.
useIsomorphicIdCreates 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.

HookDescription
useEventListenerAttaches an event listener to a target element.
useEventCallbackCreates a stable callback function that always calls the latest version of the provided callback.
useKeyComboDetects specific keyboard combinations (shortcuts).
useKeyPressDetects when a specific key is pressed down.
useLongPressDetects long press events on an element.
useRouteChangeExecutes a callback when the browser's route changes.
useThrottledEventListenerAttaches an event listener with a throttled callback.

7. Performance & Optimization

Debounce/throttle utilities, RAF helpers, and render diagnostics that keep components snappy.

HookDescription
useDebounceDebounces a value, delaying its update until a specified time has passed without change.
useDebouncedCallbackCreates a debounced version of a callback function.
useDebouncedStateA useState variant where the state updates are debounced.
useForceUpdateProvides a function to manually force a component to re-render.
useRafCallbackSchedules a callback to be executed on the next animation frame.
useRafStateA useState variant that updates state on the next animation frame.
useRenderCountTracks the number of times a component has rendered.
useRerenderProvides a function to manually trigger a re-render.
useThrottleThrottles a value, ensuring it updates at most once per specified interval.
useThrottledCallbackCreates a throttled version of a callback function.
useThrottledScrollTracks window scroll position with throttled updates.
useThrottledStateA useState variant where state updates are throttled.
useCustomCompareMemoMemo variant that reruns its factory only when a custom comparator reports dependency changes.
useSyncedRefKeeps 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.

HookDescription
useFormManages form state, input changes, and submission handling.
useFormValidationManages form state with built-in validation and submission logic.
useTranslationA basic internationalization (i18n) hook for translating form labels and messages.

9. Timers & Intervals

Declarative abstractions over setTimeout and setInterval, including countdowns and idle timers.

HookDescription
useCountdownManages a countdown timer with start, pause, and reset controls.
useIdleTimerDetects user inactivity.
useIntervalSets up an interval that repeatedly calls a function.
useIntervalWhenAn useInterval variant that only runs when a specific condition is true.
useTimeoutSets up a timeout that calls a function after a delay.

10. Animation

Hooks powered by requestAnimationFrame for smooth motion primitives.

HookDescription
useAnimationManages a basic animation loop using requestAnimationFrame.
useAnimationFrameRuns a callback function repeatedly using requestAnimationFrame.

Keywords

react

FAQs

Package last updated on 08 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts