1.3.0 โ€ข Published 1 month ago

@supunlakmal/hooks v1.3.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 month ago

@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

Okay, here is a list of all the hooks found in the provided documentation, formatted as requested:



useVisibility

Tracks whether a target element is currently visible within the browser viewport or a specified scrollable ancestor element.


useWebSocket

React hook for managing WebSocket connections.


useWakeLock

Provides a simple way to utilize the Screen Wake Lock API within your React application.


useWhyDidYouUpdate

A simple hook that helps debug component re-renders by logging the props that changed since the last render.


useWebWorker

Simplifies running functions in a separate Web Worker thread.


useWorker

Allows you to offload expensive computations or functions to a separate Web Worker thread.


useWindowSize

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


useResizeObserver

Monitors changes to the dimensions (content rect and border box) of a target DOM element using the ResizeObserver API.


useRovingTabIndex

Implements the roving tabindex accessibility pattern, enabling keyboard navigation within a group of focusable elements contained within a specified element.


useResetState

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


useScript

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


useScreenOrientation

Tracks the screen's orientation type and angle using the Screen Orientation API.


useScrollLock

Provides functions to prevent and allow scrolling on the <body> element of the page.


useScrollPosition

Tracks the current X and Y scroll position of the browser window or a specified scrollable element.


useScrollSpy

Monitors the scroll position of a container (or the window) and determines which target section element is currently considered "active".


useSessionStorage

Behaves like useState but persists the state in the browser's sessionStorage.


useRouteChange

Executes a callback function whenever the browser's URL path changes.


useSet

Manages state in the form of a JavaScript Set object, providing utility functions for common set operations.


useSetState

Provides a way to manage state in a component using an object, similar to the setState method in class components.


useSpeechSynthesis

Leverages the browser's Speech Synthesis API (Text-to-Speech).


useStateWithHistory

Manages state similarly to useState, but additionally keeps track of the state's history.


useStepper

Manages the state and navigation logic for multi-step processes.


useStorageValue

Provides a convenient way to manage state that is persisted in either localStorage or sessionStorage.


useSwipe

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


useSyncedLocalStorage

Provides a state management mechanism similar to useState, but with persistence in localStorage and synchronization across tabs.


useSyncedRef

Provides a way to create a ref that automatically stays in sync with a given value.


useTextSelection

Tracks the text currently selected by the user within the document and provides details about the selection.


useThrottle

Throttles a value, ensuring that updates to the value do not occur more frequently than a specified time limit.


useThrottledEventListener

Allows you to attach an event listener to an element and throttle the execution of the event handler.


useThrottledCallback

Creates a debounced version of a callback function, limiting the rate at which it can be executed.


useThrottledScroll

Tracks the window's horizontal (scrollX) and vertical (scrollY) scroll position, but throttles the state updates.


useThrottledState

Provides a way to throttle state updates, limiting the rate at which the state is updated based on input.


useTimeout

A declarative hook for setting timeouts (setTimeout) in React components.


useScrollToTop

Returns a function to programmatically scroll the window to the top of the page.


useToggle

Provides a simple way to manage boolean state with toggle functionality.


useNetworkSpeed

Provides information about the user's current network connection, such as effective speed and type.


useNetworkState

Provides information about the user's network connectivity status.


useNotification**

Provides an interface to interact with the browser's Web Notifications API.


useOnlineStatus

Tracks the browser's online/offline connection status.


useOrientation

Tracks the device's screen orientation using the Screen Orientation API.


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.


usePatch

A specialized version of useFetch for making PATCH requests.


usePersistentCounter

Provides a counter state which automatically persists its value in the browser's local storage.


usePersistentToggle

Manages a boolean state that automatically persists its value in the browser's local storage.


usePermission

Queries the status of browser permissions using the Permissions API.


usePinchZoom

Allows you to detect and react to pinch-to-zoom gestures on a specified HTML element.


usePortal

Simplifies the creation and management of React Portals.


usePost

A specialized version of useFetch for making POST requests.


usePrefersReducedMotion

Detects whether the user has requested the system minimize the amount of non-essential motion it uses.


usePreferredLanguages

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


usePreviousDifferent

Tracks the previous different value of a state variable.


usePromise

Provides a way to manage the state of a Promise, making it easier to handle asynchronous operations.


usePut

A specialized version of useFetch for making PUT requests.


useQueue

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


useQueryParam

Synchronizes a React state variable with a URL query parameter.


useRafCallback

Provides a way to schedule a callback function to be executed on the next animation frame using requestAnimationFrame.


usePrevious

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


useRafState

A React hook behaving like useState, but deferring state updates to the next browser animation frame using requestAnimationFrame.


useReducerLogger

A development utility hook that wraps React's built-in useReducer hook and adds automatic console logging for every action dispatched.


useIsFirstRender

Returns true if the component is rendering for the first time, and false for all subsequent renders.


useRenderCount

Tracks the number of times a component has rendered.


useIsMobile

A React hook that detects whether the current viewport is mobile-sized based on a configurable breakpoint.


useRerender

Provides a function to force a component to re-render.


useIsMounted

Provides a way to check if a component is currently mounted.


useIsomorphicId

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


useIsomorphicLayoutEffect

Uses useLayoutEffect on the client side and useEffect on the server side.


useKeyCombo

Detects specific keyboard combinations (shortcuts) being pressed.


useLifecycleLogger

Logs the component's lifecycle events to the console, such as mount, update, and unmount.


useList

Provides a convenient way to manage a list of items with common operations like adding, removing, updating, and clearing.


useKeyPress

Detects whether a specific key on the keyboard is currently being pressed down.


useListState

Provides a way to manage an array state with helper functions for common array operations.


useLocalStorage

Provides an easy way to use localStorage for state persistence across page refreshes and browser sessions.


useLocalStorageQueue

Manages a stateful queue (First-In, First-Out) that is persisted in the browser's Local Storage.


useLocalStorageValue

Provides a convenient way to manage a value stored in the browser's local storage.


useLocationBasedFetch

Provides a way to fetch data from an API endpoint based on the user's geographical location.


useLogger

A development utility hook that logs component lifecycle events and optionally prop changes to the browser console.


useLongPress

Detects long press gestures (holding down the mouse button or touch) on a target element.


useMap

Manages state in the form of a JavaScript Map object, providing utility functions for common map operations.


useMapState

Provides a convenient way to manage an object or a Map-like state in React functional components.


useMeasure

A brief paragraph explaining the purpose and functionality of the hook.


useMediaQuery

Tracks the state of a CSS media query, returning true if the query currently matches and false otherwise.


useMediaStream

Simplifies the process of requesting and managing access to the user's camera and/or microphone using the navigator.mediaDevices.getUserMedia API.


useMediatedState

Allows you to manage state that can be updated both internally and externally through a mediator function.


useMergeRefs

Merges multiple React refs (either callback refs or object refs) into a single callback ref.


useMousePosition

Tracks the current position of the mouse pointer globally within the window.


useNetworkAwareFetch

Intelligently performs data fetching using useFetch only when the user's browser is detected as being online.


useNetworkAwareWebSocket

Manages a WebSocket connection, ensuring it is active only when the user's browser is online and a valid URL is provided.


useMount

Executes a callback function exactly once when the component mounts.


useFetch

A custom React hook for fetching data from an API endpoint.


useFiniteStateMachine

Manages complex component state using an explicit state machine definition.


useFirstMountState

Provides a boolean value indicating whether the component is being mounted for the first time.


useMutation

Simplifies handling asynchronous operations that modify data (like API POST, PUT, DELETE requests).


useFocusWithinState

Determines if a specified DOM element or any of its descendant elements currently have focus.


useFocusTrap

Manages keyboard focus, trapping it within a specified container element when active.


useForceUpdate

Provides a function to force a component to re-render.


useFormValidation

A comprehensive hook for managing form state, validation (on change, blur, submit), and submission handling in React.


useFullscreen

Provides functionality to enter and exit fullscreen mode for a specific HTML element.


useFunctionalState

A brief paragraph explaining the purpose and functionality of the hook.


useGeolocation

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


useGeolocationContinuous

Provides continuous geolocation updates, allowing you to track the user's location in real-time.


useGet

A specialized version of useFetch for making GET requests.


useForm

A reusable hook for managing form state, handling input changes, and processing form submissions.


useHistoryState

Provides a way to manage state with built-in undo/redo capabilities.


useHover

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


useHookableRef

A brief paragraph explaining the purpose and functionality of the hook.


useIdleCallback

Provides a convenient way to schedule a function to be called during a browser's idle periods.


useHoverDelay

Tracks whether a user has hovered over a specific element for a minimum duration.


useIdleDetection

Interacts with the experimental Idle Detection API to monitor the user's idle state and screen lock status.


useIdleFetch

Initiates a data fetch request using useFetch only after the user becomes active following a specified period of inactivity.


useIdleTimer

Monitors user activity within the browser window and triggers callbacks when the user becomes idle or active again.


useHasBeenVisible

Determines if a referenced DOM element has ever been visible within the viewport at least once.


useImageOnLoad

Tracks the loading status, potential errors, and natural dimensions of an image element.


useInfiniteScroll

Facilitates the implementation of infinite scrolling by using the IntersectionObserver API.


useIntersectionObserver

Monitors the intersection of a target DOM element with an ancestor element or with the device's viewport.


useInterval

A declarative hook for setting intervals (setInterval) in React components.


useIntervalWhen

Sets up an interval (setInterval) which only runs when a specific condition is met.


useDebounce

Debounces a value. This hook is useful when you want to delay the execution of a function or the update of a value.


useDebouncedEffect

Similar to useEffect, but delays the execution of the effect callback until dependencies have stopped changing for a specified time.


useDebouncedCallback

Creates a debounced version of a callback function, limiting the rate at which it can be executed.


useDebouncedFetch

Wraps the Fetch API and debounces the requests.


useDebouncedGeolocation

Provides access to the device's geolocation information, but debounces the state updates.


useDarkMode

Manages application theme preference (dark/light mode).


useDebouncedMediaQuery

Determines if a CSS media query matches the current environment, but with a debounced result.


useDebouncedState

Provides a way to debounce state updates, delaying the update until the user has stopped typing for a short period.


useDebouncedWindowSize

Provides the current window dimensions, but updates the returned values only after a specified debounce delay.


useDeepCompareEffect

A drop-in replacement for React.useEffect that performs a deep comparison of its dependencies.


useDefault

Returns a default value if the provided value is null or undefined.


useDelete

A specialized version of useFetch for making DELETE requests.


useDerivedState

Computes derived state based on other values (like props or other state variables).


useDeviceMotion

Provides access to the device's motion sensor data, allowing you to track acceleration and rotation rates.


useDeviceOrientation

Tracks the physical orientation of the hosting device relative to the Earth's coordinate frame.


useDocumentTitle

Sets the document's title (document.title).


useDrag

Provides basic drag event handling for an element.


useDraggable

Adds draggability to an HTML element using pointer events.


useElementSize

Efficiently tracks the dimensions (content width and height) of a specified DOM element using the ResizeObserver API.


useEnum

A brief paragraph explaining the purpose and functionality of the hook.


useErrorBoundary

Provides state management and control functions for handling JavaScript errors within a component tree.


useEventCallback

Creates a stable function reference (memoized callback) that always delegates to the latest version of the provided callback function.


useEventListener

A robust hook for declaratively adding event listeners to the window, document, a DOM element, or a React ref.


useEventSource

Establishes and manages a connection to a Server-Sent Events (SSE) endpoint using the EventSource API.


useEyeDropper

Provides an interface to the experimental EyeDropper API, allowing users to sample colors from anywhere on their screen.


useFavicon

Dynamically sets the website's favicon.


useAnimation

Manages a simple time-based animation loop using requestAnimationFrame.


useAnimationFrame

Takes a callback function as an argument, which will be executed on each frame of the requestAnimationFrame loop.


useAsync

Simplifies handling asynchronous operations (like API calls) in React components.


useAsyncAbortable

Manages asynchronous operations, providing a way to execute an async function and abort it if needed.


useBatteryStatus

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


useBoolean

Provides a convenient way to manage a boolean state with helper functions to toggle, set to true, and set to false.


useBreakpoint

Determines the currently active responsive breakpoint based on window width.


useBroadcastChannel

Enables cross-tab/window communication between same-origin contexts using the Broadcast Channel API.


useCachedFetch

Similar to useFetch but with an added layer of simple in-memory caching.


useClickOutside

Executes a callback function when a click (or touch) event occurs outside of a specified DOM element.


useClickOutsideWithEscape

Triggers a callback function when the user either clicks outside of a specified DOM element or presses the 'Escape' key.


useClipboard

Provides functionality to interact with the system clipboard using the modern asynchronous Clipboard API.


useClipboardWithFeedback

Wraps the useClipboard hook to provide visual feedback when text has been successfully copied to the clipboard.


useConditionalEffect

Runs a side effect only when a specific condition is met.


useConst

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


useContextMenu

Provides state and logic for implementing a custom context menu (right-click menu).


useControlledRerenderState

Provides a mechanism to manually trigger re-renders of a component based on an external condition or state change.


useCookie

Provides a convenient interface for reading, writing, and deleting cookies.


useCopyToClipboard

Provides a function to copy text to the user's clipboard and tracks the success or failure status.


useCountdown

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


useCounter

Manages a numerical counter, allowing for incrementing, decrementing, and resetting.


useCustomCompareEffect

A drop-in replacement for React.useEffect that uses a custom comparison function for its dependencies.


useCustomCompareMemo

Works like useMemo but allows you to define a custom comparison function for its dependencies.


useCycle

Allows you to cycle through a list of values.


use-mobile

Determines whether the current device is a mobile device based on screen width.


useTranslation

A basic hook for handling internationalization (i18n).


useUnmountEffect

Runs its effect function only once, specifically when the component unmounts.


useUnmount

Executes a cleanup function when the component unmounts.


useUpdateEffect

Functions similarly to useEffect, but skips running the effect callback after the initial render.


useVibration

Interacts with the browser's Vibration API.


useVirtualList

A performance optimization hook for rendering long lists by only rendering visible items.

Live Demo

A live demo environment showcasing all hooks will be available here

reactreact hookscustom hooksreact utilitiesreact state managementtypescriptfrontendweb developmentjavascriptes6npm packageopen sourceui componentsuser interfaceperformance optimizationaccessibilitydeveloper toolssoftware developmentweb appssingle page applicationspareactjsreact developmentcomponent libraryreact toolkitreact componentreact patternshooks libraryhooks collectionfunctional programmingstate hookseffect hooksreact contextreact routerreact performancereact optimizationreact formform validationresponsive designmobile friendlycross platformprogressive web apppwafrontend developmentmodern javascriptbabelwebpackesnextnodejsnpmyarnmonorepocode qualitylintingtestingjestreact testing librarycontinuous integrationci cddevopstypescript hooksreact typescriptreact 18concurrent modesuspensereact suspensehooks best practicesreact best practicesreact communityfrontend toolsweb performancereact animationdrag and dropaccessibility hookskeyboard navigationseo friendlycode reusemodular codeclean codereact stateimmutable statereact lifecyclereact hooks tutorialreact hooks examplesreact hooks libraryhooksutility hooksstate managementperformanceuseToggleuseDebounceuseFetchuseAsyncuseLocalStorageuseSessionStorageuseClickOutsideuseEventListeneruseWindowSizeuseFormuseValidationuseIntervaluseTimeoutusePrevioususeIntersectionObserveruseVirtualListusePaginationuseDarkModeuseClipboarduseWebSocketuseScrolluseAnimationuseDraguseDraggableuseFocusTrapuseMediaQuerybrowser apiuseAnimationuseAsyncAbortableuseBreakpointuseBroadcastChanneluseCachedFetchuseClipboarduseContextMenuuseCopyToClipboarduseControlledRerenderStateuseCountdownuseCounteruseConditionalEffectuseDarkModeuseDebouncedStateuseDebouncedFetchuseDebouncedGeolocationuseDebouncedMediaQueryuseDeepCompareEffectuseDebouncedCallbackuseDebouncedEffectuseDerivedStateuseDefaultuseDocumentTitleuseDeviceMotionuseLocationBasedFetchuseDeviceOrientationuseEyeDropperuseFaviconuseGeolocationContinuoususeErrorBoundaryuseMobileuseNewFullscreenuseElementSizeuseFirstMountStateuseFiniteStateMachineuseFormValidationuseFullscreenuseGeolocationuseHoveruseFunctionalStateuseHookableRefuseIsMounteduseIsomorphicLayoutEffectuseLifecycleLoggeruseListuseLocalStorageValueuseLocalStorageQueueuseMediaStreamuseMeasureuseMediatedStateuseCustomCompareEffectuseCustomCompareMemousePreviousDifferentusePersistentToggleuseInfiniteScrolluseIsFirstRenderuseKeyCombouseKeyPressuseLogger
1.3.0

1 month ago

1.2.0

2 months ago

1.0.5

2 months ago

1.0.4

2 months ago

1.0.3

2 months ago

1.0.0

2 months ago

0.12.0

2 months ago

0.11.0

2 months ago

0.10.1

2 months ago

0.10.0

2 months ago

0.9.0

2 months ago

0.8.0

2 months ago

0.7.0

2 months ago

0.6.0

2 months ago

0.5.0

2 months ago

0.4.0

2 months ago

0.3.0

2 months ago

0.2.1

2 months ago

0.2.0

2 months ago

0.1.14

3 months ago

0.1.13

3 months ago

0.1.12

3 months ago

0.1.11

3 months ago

0.1.10

3 months ago

0.1.9

3 months ago

0.1.8

3 months ago

0.1.7

3 months ago

0.1.6

3 months ago