🎩 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

Source
npmnpm
Version
0.10.1
Version published
Weekly downloads
80
-73.24%
Maintainers
1
Weekly downloads
 
Created
Source

@supunlakmal/hooks

NPM Version License: ISC TypeScript

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
# 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:

HookDescription
useAnimationManages a simple time-based animation loop using requestAnimationFrame.
useAsyncSimplifies handling asynchronous operations (like API calls), managing loading, error, and success states.
useAsyncAbortableSimplifies handling asynchronous operations that can be aborted.
useBreakpointDetermines the currently active responsive breakpoint based on window width.
useBroadcastChannelEnables cross-tab/window communication using the Broadcast Channel API.
useCachedFetchA useFetch variant with simple in-memory caching and TTL.
useClickOutsideExecutes a callback when a click/touch event occurs outside of a specified DOM element.
useClipboardProvides functionality to interact with the system clipboard (copy/paste).
useContextMenuProvides state and logic for implementing a custom context menu (right-click menu).
useCopyToClipboardProvides a function to copy text to the clipboard and tracks status (uses fallback).
useControlledRerenderStateA hook to force a component to re-render
useCountdownManages a countdown timer with start, pause, and reset controls.
useCounterA basic counter hook
useConditionalEffectA useEffect variant that allows you to conditionally run the effect.
useDarkModeManages application theme preference (dark/light mode) with OS detection and local storage persistence.
useDebouncedStateDebounces a state, delaying updates until a certain time has passed without changes.
useDebounceDebounces a value, delaying updates until a certain time has passed without changes.
useDeepCompareEffectA useEffect variant that performs a deep comparison of dependencies.
useDebouncedCallbackDebounces a callback function, delaying its execution until a certain time has passed without changes.
useDebouncedEffectA useEffect variant that debounces the effect callback.
useDerivedStateComputes derived state based on other values, recomputing only when dependencies change (wraps useMemo).
useDeviceMotionTracks device motion information (acceleration, rotation rate) via the devicemotion event.
useDeviceOrientationTracks the physical orientation of the device via the deviceorientation event.
useDragProvides basic HTML Drag and Drop API event handling (dragstart, drag, dragend) for an element.
useConditionalEffectA useEffect variant that allows you to conditionally run the effect.
useCounterA basic counter hook
useGeolocationContinuousTracks the user's geographic location continuously using the Geolocation API.
useErrorBoundaryA hook to add error boundary to a component
useMobileDetects if the current viewport is mobile-sized based on a configurable breakpoint
useNewFullscreenEnters and exits fullscreen mode for an element, tracking the current state.
useDraggableAdds direct element draggability (positioning via transform) using pointer events, with bounds support.
useElementSizeEfficiently tracks the dimensions (width/height) of a DOM element using ResizeObserver.
useFirstMountStateReturns true if the component is rendering for the first time, false otherwise.
useEventListenerRobustly attaches event listeners to window, document, or elements, handling cleanup.
useFetchA simple hook for fetching data, managing loading and error states.
useFiniteStateMachineManages complex component state using an explicit state machine definition.
useFocusTrapTraps keyboard focus within a specified container element when active (for modals, dialogs).
useFormA basic hook for managing form state, input changes, and submission.
useFormValidationA comprehensive hook for form state, validation (change/blur/submit), and submission handling.
useFullscreenEnters and exits fullscreen mode for an element, tracking the current state.
useGeolocationTracks the user's geographic location using the Geolocation API.
useHoverTracks whether the mouse pointer is currently hovering over a specific DOM element.
useFunctionalStateFunctional state updates for React components.
useHookableRefCreate a ref that can be used in a hook.
useIsMountedA hook that returns true if the component is mounted.
useIsomorphicLayoutEffectA useLayoutEffect variant that works on the server and the client.
useLifecycleLoggerA hook that logs the component's lifecycle events.
useListA hook that provides functions to manipulate a list.
useLocalStorageValueGet the value from local storage.
useMeasureGet the size of an element
useMediatedStateManages a mediated state value.
useCustomCompareEffectA useEffect variant that allow to provide custom compore logic
useCustomCompareMemoA useMemo variant that allow to provide custom compore logic
usePreviousDifferentTracks the previous different value of a state or prop from the last render.
useInfiniteScrollFacilitates infinite scrolling using IntersectionObserver to trigger loading more data.
useIntersectionObserverMonitors the intersection of a target element with the viewport or an ancestor.
useIntervalA declarative hook for setting intervals (setInterval) with automatic cleanup.
useIsFirstRenderReturns true if the component is rendering for the first time, false otherwise.
useKeyComboDetects specific keyboard combinations (shortcuts) being pressed.
useKeyPressDetects whether a specific key is currently being pressed down.
useLocalStorageManages state persisted in localStorage, synchronizing across tabs.
useLoggerDevelopment utility to log component lifecycle events and prop changes.
useLongPressDetects long press gestures (mouse or touch) on a target element.
useMapManages state in the form of a JavaScript Map, providing immutable update actions.
useMediaQueryTracks the state of a CSS media query (e.g., viewport size, orientation, color scheme).
useNetworkStateTracks the network state.
useMergeRefsMerges multiple React refs (callback or object refs) into a single callback ref.
useMountExecutes a callback function exactly once when the component mounts.
useMutationSimplifies handling asynchronous data modification operations (POST, PUT, DELETE), managing status.
useNetworkSpeedProvides information about the user's network connection (speed, type) using the Network Information API.
usePromiseSimplifies handling promises, managing loading, error, and success states.
useOnlineStatusTracks the browser's online/offline connection status.
usePageVisibilityTracks the visibility state of the current browser tab/page using the Page Visibility API.
useOldUpdateEffectA useEffect variant that skips the effect execution after the initial render (mount).
usePaginationManages pagination logic for client-side data sets.
usePermissionQueries the status of browser permissions (geolocation, notifications, etc.) using the Permissions API.
usePortalSimplifies the creation and management of React Portals.
usePreviousTracks the previous value of a state or prop from the last render.
useQueryParamSynchronizes a React state variable with a URL query parameter.
useReducerLoggerWraps useReducer to automatically log actions and state changes in development.
useRenderCountTracks the number of times a component has rendered.
useRafCallbackCreates a callback based on requestAnimationFrame.
useResizeObserverMonitors changes to the dimensions of a target element using the ResizeObserver API.
useRouteChangeExecutes a callback whenever the browser's URL path changes (handles popstate and pushState).
useRovingTabIndexImplements the roving tabindex accessibility pattern for keyboard navigation within a group.
useScrollPositionTracks the current X and Y scroll position of the window or a specified element.
useScrollSpyMonitors scroll position to determine which section element is currently active in the viewport.
useScrollToTopProvides a function to programmatically scroll the window to the top.
useSessionStorageManages state persisted in sessionStorage for the duration of the session.
useSetManages state in the form of a JavaScript Set, providing immutable update actions.
useStateWithHistoryManages state with undo/redo history tracking.
useRerenderForce to re-render the component.
useSwipeDetects swipe gestures (left, right, up, down) on touch-enabled devices for a specified element.
useThrottleThrottles a value, ensuring updates do not occur more frequently than a specified limit.
useStepperA hook to use a basic step logic.
useStorageValueA hook to get the value from local or session storage.
useThrottledStateThrottles a state, ensuring updates do not occur more frequently than a specified limit.
useThrottledCallbackThrottles a callback, ensuring updates do not occur more frequently than a specified limit.
useTimeoutA declarative hook for setting timeouts (setTimeout) with automatic cleanup.
useToggleManages boolean state with convenient toggle, setOn, and setOff functions.
useTranslationA basic hook for handling internationalization (i18n) with static resources.
useUnmountExecutes a cleanup function exactly once when the component unmounts.
useUpdateEffectA useEffect variant that skips the effect execution after the initial render (mount).
useVirtualListPerformance optimization for rendering long lists by rendering only visible items (fixed height).
useSyncedRefCreate a ref that syncs with another value
useUnmountEffectExecutes a cleanup function when the component unmounts.
useVisibilityTracks whether a target element is currently visible within the viewport or an ancestor using IntersectionObserver.
useWebSocketManages WebSocket connections, state, messaging, and automatic reconnection.
useWindowSizeReturns the current dimensions (width and height) of the browser window.
useWhyDidYouUpdateDevelopment utility to debug component re-renders by logging changed props.
useWakeLockManages the Screen Wake Lock API to prevent the screen from sleeping.
useWebWorkerRuns a function in a Web Worker thread to offload heavy computations from the main thread.
useWorkerOffloads 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

Keywords

react

FAQs

Package last updated on 05 May 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