
Security News
Suno Breached via Shai-Hulud Worm, Leaked Code Exposes AI Music Scraping
A Shai-Hulud infection exposed Suno's source code, which shows the AI music startup stream-ripped tracks to train its models.
@supunlakmal/hooks
Advanced tools
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?
useDebounce, useThrottle, and useVirtualList for optimization.npm install @supunlakmal/hooks
# or
yarn add @supunlakmal/hooks
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>
);
}
Okay, here is a list of all the hooks found in the provided documentation, formatted as requested:
useVisibilityTracks whether a target element is currently visible within the browser viewport or a specified scrollable ancestor element.
useWebSocketReact hook for managing WebSocket connections.
useWakeLockProvides a simple way to utilize the Screen Wake Lock API within your React application.
useWhyDidYouUpdateA simple hook that helps debug component re-renders by logging the props that changed since the last render.
useWebWorkerSimplifies running functions in a separate Web Worker thread.
useWorkerAllows you to offload expensive computations or functions to a separate Web Worker thread.
useWindowSizeReturns the current dimensions (width and height) of the browser window.
useResizeObserverMonitors changes to the dimensions (content rect and border box) of a target DOM element using the ResizeObserver API.
useRovingTabIndexImplements the roving tabindex accessibility pattern, enabling keyboard navigation within a group of focusable elements contained within a specified element.
useResetStateProvides a state variable and a function to reset it to its initial value.
useScriptDynamically loads an external JavaScript script and tracks its loading status.
useScreenOrientationTracks the screen's orientation type and angle using the Screen Orientation API.
useScrollLockProvides functions to prevent and allow scrolling on the <body> element of the page.
useScrollPositionTracks the current X and Y scroll position of the browser window or a specified scrollable element.
useScrollSpyMonitors the scroll position of a container (or the window) and determines which target section element is currently considered "active".
useSessionStorageBehaves like useState but persists the state in the browser's sessionStorage.
useRouteChangeExecutes a callback function whenever the browser's URL path changes.
useSetManages state in the form of a JavaScript Set object, providing utility functions for common set operations.
useSetStateProvides a way to manage state in a component using an object, similar to the setState method in class components.
useSpeechSynthesisLeverages the browser's Speech Synthesis API (Text-to-Speech).
useStateWithHistoryManages state similarly to useState, but additionally keeps track of the state's history.
useStepperManages the state and navigation logic for multi-step processes.
useStorageValueProvides a convenient way to manage state that is persisted in either localStorage or sessionStorage.
useSwipeDetects swipe gestures (left, right, up, down) on touch-enabled devices for a specified element.
useSyncedLocalStorageProvides a state management mechanism similar to useState, but with persistence in localStorage and synchronization across tabs.
useSyncedRefProvides a way to create a ref that automatically stays in sync with a given value.
useTextSelectionTracks the text currently selected by the user within the document and provides details about the selection.
useThrottleThrottles a value, ensuring that updates to the value do not occur more frequently than a specified time limit.
useThrottledEventListenerAllows you to attach an event listener to an element and throttle the execution of the event handler.
useThrottledCallbackCreates a debounced version of a callback function, limiting the rate at which it can be executed.
useThrottledScrollTracks the window's horizontal (scrollX) and vertical (scrollY) scroll position, but throttles the state updates.
useThrottledStateProvides a way to throttle state updates, limiting the rate at which the state is updated based on input.
useTimeoutA declarative hook for setting timeouts (setTimeout) in React components.
useScrollToTopReturns a function to programmatically scroll the window to the top of the page.
useToggleProvides a simple way to manage boolean state with toggle functionality.
useNetworkSpeedProvides information about the user's current network connection, such as effective speed and type.
useNetworkStateProvides information about the user's network connectivity status.
useNotification****Provides an interface to interact with the browser's Web Notifications API.
useOnlineStatusTracks the browser's online/offline connection status.
useOrientationTracks the device's screen orientation using the Screen Orientation API.
usePageLeaveTriggers a callback function when the user's mouse cursor leaves the main browser window or document area.
usePageVisibilityTracks the visibility state of the current browser tab/page using the Page Visibility API.
usePaginationManages pagination logic for client-side data sets.
usePatchA specialized version of useFetch for making PATCH requests.
usePersistentCounterProvides a counter state which automatically persists its value in the browser's local storage.
usePersistentToggleManages a boolean state that automatically persists its value in the browser's local storage.
usePermissionQueries the status of browser permissions using the Permissions API.
usePinchZoomAllows you to detect and react to pinch-to-zoom gestures on a specified HTML element.
usePortalSimplifies the creation and management of React Portals.
usePostA specialized version of useFetch for making POST requests.
usePrefersReducedMotionDetects whether the user has requested the system minimize the amount of non-essential motion it uses.
usePreferredLanguagesReturns an array of the user's preferred languages, as configured in their browser.
usePreviousDifferentTracks the previous different value of a state variable.
usePromiseProvides a way to manage the state of a Promise, making it easier to handle asynchronous operations.
usePutA specialized version of useFetch for making PUT requests.
useQueueManages a stateful queue (First-In, First-Out).
useQueryParamSynchronizes a React state variable with a URL query parameter.
useRafCallbackProvides a way to schedule a callback function to be executed on the next animation frame using requestAnimationFrame.
usePreviousTracks the previous value of a given state or prop from the last render.
useRafStateA React hook behaving like useState, but deferring state updates to the next browser animation frame using requestAnimationFrame.
useReducerLoggerA development utility hook that wraps React's built-in useReducer hook and adds automatic console logging for every action dispatched.
useIsFirstRenderReturns true if the component is rendering for the first time, and false for all subsequent renders.
useRenderCountTracks the number of times a component has rendered.
useIsMobileA React hook that detects whether the current viewport is mobile-sized based on a configurable breakpoint.
useRerenderProvides a function to force a component to re-render.
useIsMountedProvides a way to check if a component is currently mounted.
useIsomorphicIdGenerates unique IDs that are stable and consistent across server and client rendering environments.
useIsomorphicLayoutEffectUses useLayoutEffect on the client side and useEffect on the server side.
useKeyComboDetects specific keyboard combinations (shortcuts) being pressed.
useLifecycleLoggerLogs the component's lifecycle events to the console, such as mount, update, and unmount.
useListProvides a convenient way to manage a list of items with common operations like adding, removing, updating, and clearing.
useKeyPressDetects whether a specific key on the keyboard is currently being pressed down.
useListStateProvides a way to manage an array state with helper functions for common array operations.
useLocalStorageProvides an easy way to use localStorage for state persistence across page refreshes and browser sessions.
useLocalStorageQueueManages a stateful queue (First-In, First-Out) that is persisted in the browser's Local Storage.
useLocalStorageValueProvides a convenient way to manage a value stored in the browser's local storage.
useLocationBasedFetchProvides a way to fetch data from an API endpoint based on the user's geographical location.
useLoggerA development utility hook that logs component lifecycle events and optionally prop changes to the browser console.
useLongPressDetects long press gestures (holding down the mouse button or touch) on a target element.
useMapManages state in the form of a JavaScript Map object, providing utility functions for common map operations.
useMapStateProvides a convenient way to manage an object or a Map-like state in React functional components.
useMeasureA brief paragraph explaining the purpose and functionality of the hook.
useMediaQueryTracks the state of a CSS media query, returning true if the query currently matches and false otherwise.
useMediaStreamSimplifies the process of requesting and managing access to the user's camera and/or microphone using the navigator.mediaDevices.getUserMedia API.
useMediatedStateAllows you to manage state that can be updated both internally and externally through a mediator function.
useMergeRefsMerges multiple React refs (either callback refs or object refs) into a single callback ref.
useMousePositionTracks the current position of the mouse pointer globally within the window.
useNetworkAwareFetchIntelligently performs data fetching using useFetch only when the user's browser is detected as being online.
useNetworkAwareWebSocketManages a WebSocket connection, ensuring it is active only when the user's browser is online and a valid URL is provided.
useMountExecutes a callback function exactly once when the component mounts.
useFetchA custom React hook for fetching data from an API endpoint.
useFiniteStateMachineManages complex component state using an explicit state machine definition.
useFirstMountStateProvides a boolean value indicating whether the component is being mounted for the first time.
useMutationSimplifies handling asynchronous operations that modify data (like API POST, PUT, DELETE requests).
useFocusWithinStateDetermines if a specified DOM element or any of its descendant elements currently have focus.
useFocusTrapManages keyboard focus, trapping it within a specified container element when active.
useForceUpdateProvides a function to force a component to re-render.
useFormValidationA comprehensive hook for managing form state, validation (on change, blur, submit), and submission handling in React.
useFullscreenProvides functionality to enter and exit fullscreen mode for a specific HTML element.
useFunctionalStateA brief paragraph explaining the purpose and functionality of the hook.
useGeolocationTracks the user's current geographic location using the browser's Geolocation API.
useGeolocationContinuousProvides continuous geolocation updates, allowing you to track the user's location in real-time.
useGetA specialized version of useFetch for making GET requests.
useFormA reusable hook for managing form state, handling input changes, and processing form submissions.
useHistoryStateProvides a way to manage state with built-in undo/redo capabilities.
useHoverTracks whether the mouse pointer is currently hovering over a specific DOM element.
useHookableRefA brief paragraph explaining the purpose and functionality of the hook.
useIdleCallbackProvides a convenient way to schedule a function to be called during a browser's idle periods.
useHoverDelayTracks whether a user has hovered over a specific element for a minimum duration.
useIdleDetectionInteracts with the experimental Idle Detection API to monitor the user's idle state and screen lock status.
useIdleFetchInitiates a data fetch request using useFetch only after the user becomes active following a specified period of inactivity.
useIdleTimerMonitors user activity within the browser window and triggers callbacks when the user becomes idle or active again.
useHasBeenVisibleDetermines if a referenced DOM element has ever been visible within the viewport at least once.
useImageOnLoadTracks the loading status, potential errors, and natural dimensions of an image element.
useInfiniteScrollFacilitates the implementation of infinite scrolling by using the IntersectionObserver API.
useIntersectionObserverMonitors the intersection of a target DOM element with an ancestor element or with the device's viewport.
useIntervalA declarative hook for setting intervals (setInterval) in React components.
useIntervalWhenSets up an interval (setInterval) which only runs when a specific condition is met.
useDebounceDebounces a value. This hook is useful when you want to delay the execution of a function or the update of a value.
useDebouncedEffectSimilar to useEffect, but delays the execution of the effect callback until dependencies have stopped changing for a specified time.
useDebouncedCallbackCreates a debounced version of a callback function, limiting the rate at which it can be executed.
useDebouncedFetchWraps the Fetch API and debounces the requests.
useDebouncedGeolocationProvides access to the device's geolocation information, but debounces the state updates.
useDarkModeManages application theme preference (dark/light mode).
useDebouncedMediaQueryDetermines if a CSS media query matches the current environment, but with a debounced result.
useDebouncedStateProvides a way to debounce state updates, delaying the update until the user has stopped typing for a short period.
useDebouncedWindowSizeProvides the current window dimensions, but updates the returned values only after a specified debounce delay.
useDeepCompareEffectA drop-in replacement for React.useEffect that performs a deep comparison of its dependencies.
useDefaultReturns a default value if the provided value is null or undefined.
useDeleteA specialized version of useFetch for making DELETE requests.
useDerivedStateComputes derived state based on other values (like props or other state variables).
useDeviceMotionProvides access to the device's motion sensor data, allowing you to track acceleration and rotation rates.
useDeviceOrientationTracks the physical orientation of the hosting device relative to the Earth's coordinate frame.
useDocumentTitleSets the document's title (document.title).
useDragProvides basic drag event handling for an element.
useDraggableAdds draggability to an HTML element using pointer events.
useElementSizeEfficiently tracks the dimensions (content width and height) of a specified DOM element using the ResizeObserver API.
useEnumA brief paragraph explaining the purpose and functionality of the hook.
useErrorBoundaryProvides state management and control functions for handling JavaScript errors within a component tree.
useEventCallbackCreates a stable function reference (memoized callback) that always delegates to the latest version of the provided callback function.
useEventListenerA robust hook for declaratively adding event listeners to the window, document, a DOM element, or a React ref.
useEventSourceEstablishes and manages a connection to a Server-Sent Events (SSE) endpoint using the EventSource API.
useEyeDropperProvides an interface to the experimental EyeDropper API, allowing users to sample colors from anywhere on their screen.
useFaviconDynamically sets the website's favicon.
useAnimationManages a simple time-based animation loop using requestAnimationFrame.
useAnimationFrameTakes a callback function as an argument, which will be executed on each frame of the requestAnimationFrame loop.
useAsyncSimplifies handling asynchronous operations (like API calls) in React components.
useAsyncAbortableManages asynchronous operations, providing a way to execute an async function and abort it if needed.
useBatteryStatusProvides real-time information about the device's battery status.
useBooleanProvides a convenient way to manage a boolean state with helper functions to toggle, set to true, and set to false.
useBreakpointDetermines the currently active responsive breakpoint based on window width.
useBroadcastChannelEnables cross-tab/window communication between same-origin contexts using the Broadcast Channel API.
useCachedFetchSimilar to useFetch but with an added layer of simple in-memory caching.
useClickOutsideExecutes a callback function when a click (or touch) event occurs outside of a specified DOM element.
useClickOutsideWithEscapeTriggers a callback function when the user either clicks outside of a specified DOM element or presses the 'Escape' key.
useClipboardProvides functionality to interact with the system clipboard using the modern asynchronous Clipboard API.
useClipboardWithFeedbackWraps the useClipboard hook to provide visual feedback when text has been successfully copied to the clipboard.
useConditionalEffectRuns a side effect only when a specific condition is met.
useConstInitializes and returns a value that remains constant throughout the component's lifecycle.
useContextMenuProvides state and logic for implementing a custom context menu (right-click menu).
useControlledRerenderStateProvides a mechanism to manually trigger re-renders of a component based on an external condition or state change.
useCookieProvides a convenient interface for reading, writing, and deleting cookies.
useCopyToClipboardProvides a function to copy text to the user's clipboard and tracks the success or failure status.
useCountdownManages a countdown timer with start, pause, and reset controls.
useCounterManages a numerical counter, allowing for incrementing, decrementing, and resetting.
useCustomCompareEffectA drop-in replacement for React.useEffect that uses a custom comparison function for its dependencies.
useCustomCompareMemoWorks like useMemo but allows you to define a custom comparison function for its dependencies.
useCycleAllows you to cycle through a list of values.
use-mobileDetermines whether the current device is a mobile device based on screen width.
useTranslationA basic hook for handling internationalization (i18n).
useUnmountEffectRuns its effect function only once, specifically when the component unmounts.
useUnmountExecutes a cleanup function when the component unmounts.
useUpdateEffectFunctions similarly to useEffect, but skips running the effect callback after the initial render.
useVibrationInteracts with the browser's Vibration API.
useVirtualListA performance optimization hook for rendering long lists by only rendering visible items.
A live demo environment showcasing all hooks will be available here
FAQs
A collection of reusable React hooks
The npm package @supunlakmal/hooks receives a total of 215 weekly downloads. As such, @supunlakmal/hooks popularity was classified as not popular.
We found that @supunlakmal/hooks demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.ย It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Security News
A Shai-Hulud infection exposed Suno's source code, which shows the AI music startup stream-ripped tracks to train its models.

Security News
Vercel is formalizing a monthly release program for Next.js. The change follows React2Shell and a sharp rise in AI-assisted vulnerability discovery.

Research
/Security News
11 malicious NuGet tools pose as game cheats to deploy Windows payloads, track hosts, and use Google Sheets for telemetry and control.