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
, anduseVirtualList
for optimization. - đź§© Minimal Dependencies: Core hooks have zero runtime dependencies (unless specified in individual hook docs).
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:
Tracks whether a target element is currently visible within the browser viewport or a specified scrollable ancestor element.
React hook for managing WebSocket connections.
Provides a simple way to utilize the Screen Wake Lock API within your React application.
A simple hook that helps debug component re-renders by logging the props that changed since the last render.
Simplifies running functions in a separate Web Worker thread.
Allows you to offload expensive computations or functions to a separate Web Worker thread.
Returns the current dimensions (width and height) of the browser window.
Monitors changes to the dimensions (content rect and border box) of a target DOM element using the ResizeObserver
API.
Implements the roving tabindex accessibility pattern, enabling keyboard navigation within a group of focusable elements contained within a specified element.
Provides a state variable and a function to reset it to its initial value.
Dynamically loads an external JavaScript script and tracks its loading status.
Tracks the screen's orientation type and angle using the Screen Orientation API.
Provides functions to prevent and allow scrolling on the <body>
element of the page.
Tracks the current X and Y scroll position of the browser window or a specified scrollable element.
Monitors the scroll position of a container (or the window) and determines which target section element is currently considered "active".
Behaves like useState
but persists the state in the browser's sessionStorage
.
Executes a callback function whenever the browser's URL path changes.
Manages state in the form of a JavaScript Set
object, providing utility functions for common set operations.
Provides a way to manage state in a component using an object, similar to the setState
method in class components.
Leverages the browser's Speech Synthesis API (Text-to-Speech).
Manages state similarly to useState
, but additionally keeps track of the state's history.
Manages the state and navigation logic for multi-step processes.
Provides a convenient way to manage state that is persisted in either localStorage
or sessionStorage
.
Detects swipe gestures (left, right, up, down) on touch-enabled devices for a specified element.
Provides a state management mechanism similar to useState
, but with persistence in localStorage
and synchronization across tabs.
Provides a way to create a ref that automatically stays in sync with a given value.
Tracks the text currently selected by the user within the document and provides details about the selection.
Throttles a value, ensuring that updates to the value do not occur more frequently than a specified time limit.
Allows you to attach an event listener to an element and throttle the execution of the event handler.
Creates a debounced version of a callback function, limiting the rate at which it can be executed.
Tracks the window's horizontal (scrollX
) and vertical (scrollY
) scroll position, but throttles the state updates.
Provides a way to throttle state updates, limiting the rate at which the state is updated based on input.
A declarative hook for setting timeouts (setTimeout
) in React components.
Returns a function to programmatically scroll the window to the top of the page.
Provides a simple way to manage boolean state with toggle functionality.
Provides information about the user's current network connection, such as effective speed and type.
Provides information about the user's network connectivity status.
Provides an interface to interact with the browser's Web Notifications API.
Tracks the browser's online/offline connection status.
Tracks the device's screen orientation using the Screen Orientation API.
Triggers a callback function when the user's mouse cursor leaves the main browser window or document area.
Tracks the visibility state of the current browser tab/page using the Page Visibility API.
Manages pagination logic for client-side data sets.
A specialized version of useFetch
for making PATCH requests.
Provides a counter state which automatically persists its value in the browser's local storage.
Manages a boolean state that automatically persists its value in the browser's local storage.
Queries the status of browser permissions using the Permissions API.
Allows you to detect and react to pinch-to-zoom gestures on a specified HTML element.
Simplifies the creation and management of React Portals.
A specialized version of useFetch
for making POST requests.
Detects whether the user has requested the system minimize the amount of non-essential motion it uses.
Returns an array of the user's preferred languages, as configured in their browser.
Tracks the previous different value of a state variable.
Provides a way to manage the state of a Promise, making it easier to handle asynchronous operations.
A specialized version of useFetch
for making PUT requests.
Manages a stateful queue (First-In, First-Out).
Synchronizes a React state variable with a URL query parameter.
Provides a way to schedule a callback function to be executed on the next animation frame using requestAnimationFrame
.
Tracks the previous value of a given state or prop from the last render.
A React hook behaving like useState
, but deferring state updates to the next browser animation frame using requestAnimationFrame
.
A development utility hook that wraps React's built-in useReducer
hook and adds automatic console logging for every action dispatched.
Returns true
if the component is rendering for the first time, and false
for all subsequent renders.
Tracks the number of times a component has rendered.
A React hook that detects whether the current viewport is mobile-sized based on a configurable breakpoint.
Provides a function to force a component to re-render.
Provides a way to check if a component is currently mounted.
Generates unique IDs that are stable and consistent across server and client rendering environments.
Uses useLayoutEffect
on the client side and useEffect
on the server side.
Detects specific keyboard combinations (shortcuts) being pressed.
Logs the component's lifecycle events to the console, such as mount, update, and unmount.
Provides a convenient way to manage a list of items with common operations like adding, removing, updating, and clearing.
Detects whether a specific key on the keyboard is currently being pressed down.
Provides a way to manage an array state with helper functions for common array operations.
Provides an easy way to use localStorage
for state persistence across page refreshes and browser sessions.
Manages a stateful queue (First-In, First-Out) that is persisted in the browser's Local Storage.
Provides a convenient way to manage a value stored in the browser's local storage.
Provides a way to fetch data from an API endpoint based on the user's geographical location.
A development utility hook that logs component lifecycle events and optionally prop changes to the browser console.
Detects long press gestures (holding down the mouse button or touch) on a target element.
Manages state in the form of a JavaScript Map
object, providing utility functions for common map operations.
Provides a convenient way to manage an object or a Map-like state in React functional components.
A brief paragraph explaining the purpose and functionality of the hook.
Tracks the state of a CSS media query, returning true
if the query currently matches and false
otherwise.
Simplifies the process of requesting and managing access to the user's camera and/or microphone using the navigator.mediaDevices.getUserMedia
API.
Allows you to manage state that can be updated both internally and externally through a mediator function.
Merges multiple React refs (either callback refs or object refs) into a single callback ref.
Tracks the current position of the mouse pointer globally within the window.
Intelligently performs data fetching using useFetch
only when the user's browser is detected as being online.
Manages a WebSocket connection, ensuring it is active only when the user's browser is online and a valid URL is provided.
Executes a callback function exactly once when the component mounts.
A custom React hook for fetching data from an API endpoint.
Manages complex component state using an explicit state machine definition.
Provides a boolean value indicating whether the component is being mounted for the first time.
Simplifies handling asynchronous operations that modify data (like API POST, PUT, DELETE requests).
Determines if a specified DOM element or any of its descendant elements currently have focus.
Manages keyboard focus, trapping it within a specified container element when active.
Provides a function to force a component to re-render.
A comprehensive hook for managing form state, validation (on change, blur, submit), and submission handling in React.
Provides functionality to enter and exit fullscreen mode for a specific HTML element.
A brief paragraph explaining the purpose and functionality of the hook.
Tracks the user's current geographic location using the browser's Geolocation API.
Provides continuous geolocation updates, allowing you to track the user's location in real-time.
A specialized version of useFetch
for making GET requests.
A reusable hook for managing form state, handling input changes, and processing form submissions.
Provides a way to manage state with built-in undo/redo capabilities.
Tracks whether the mouse pointer is currently hovering over a specific DOM element.
A brief paragraph explaining the purpose and functionality of the hook.
Provides a convenient way to schedule a function to be called during a browser's idle periods.
Tracks whether a user has hovered over a specific element for a minimum duration.
Interacts with the experimental Idle Detection API to monitor the user's idle state and screen lock status.
Initiates a data fetch request using useFetch
only after the user becomes active following a specified period of inactivity.
Monitors user activity within the browser window and triggers callbacks when the user becomes idle or active again.
Determines if a referenced DOM element has ever been visible within the viewport at least once.
Tracks the loading status, potential errors, and natural dimensions of an image element.
Facilitates the implementation of infinite scrolling by using the IntersectionObserver
API.
Monitors the intersection of a target DOM element with an ancestor element or with the device's viewport.
A declarative hook for setting intervals (setInterval
) in React components.
Sets up an interval (setInterval
) which only runs when a specific condition is met.
Debounces a value. This hook is useful when you want to delay the execution of a function or the update of a value.
Similar to useEffect
, but delays the execution of the effect callback until dependencies have stopped changing for a specified time.
Creates a debounced version of a callback function, limiting the rate at which it can be executed.
Wraps the Fetch API and debounces the requests.
Provides access to the device's geolocation information, but debounces the state updates.
Manages application theme preference (dark/light mode).
Determines if a CSS media query matches the current environment, but with a debounced result.
Provides a way to debounce state updates, delaying the update until the user has stopped typing for a short period.
Provides the current window dimensions, but updates the returned values only after a specified debounce delay.
A drop-in replacement for React.useEffect
that performs a deep comparison of its dependencies.
Returns a default value if the provided value is null
or undefined
.
A specialized version of useFetch
for making DELETE requests.
Computes derived state based on other values (like props or other state variables).
Provides access to the device's motion sensor data, allowing you to track acceleration and rotation rates.
Tracks the physical orientation of the hosting device relative to the Earth's coordinate frame.
Sets the document's title (document.title
).
Provides basic drag event handling for an element.
Adds draggability to an HTML element using pointer events.
Efficiently tracks the dimensions (content width and height) of a specified DOM element using the ResizeObserver
API.
A brief paragraph explaining the purpose and functionality of the hook.
Provides state management and control functions for handling JavaScript errors within a component tree.
Creates a stable function reference (memoized callback) that always delegates to the latest version of the provided callback function.
A robust hook for declaratively adding event listeners to the window
, document
, a DOM element, or a React ref.
Establishes and manages a connection to a Server-Sent Events (SSE) endpoint using the EventSource
API.
Provides an interface to the experimental EyeDropper API, allowing users to sample colors from anywhere on their screen.
Dynamically sets the website's favicon.
Manages a simple time-based animation loop using requestAnimationFrame
.
Takes a callback function as an argument, which will be executed on each frame of the requestAnimationFrame
loop.
Simplifies handling asynchronous operations (like API calls) in React components.
Manages asynchronous operations, providing a way to execute an async function and abort it if needed.
Provides real-time information about the device's battery status.
Provides a convenient way to manage a boolean state with helper functions to toggle, set to true, and set to false.
Determines the currently active responsive breakpoint based on window width.
Enables cross-tab/window communication between same-origin contexts using the Broadcast Channel API.
Similar to useFetch
but with an added layer of simple in-memory caching.
Executes a callback function when a click (or touch) event occurs outside of a specified DOM element.
Triggers a callback function when the user either clicks outside of a specified DOM element or presses the 'Escape' key.
Provides functionality to interact with the system clipboard using the modern asynchronous Clipboard API.
Wraps the useClipboard
hook to provide visual feedback when text has been successfully copied to the clipboard.
Runs a side effect only when a specific condition is met.
Initializes and returns a value that remains constant throughout the component's lifecycle.
Provides state and logic for implementing a custom context menu (right-click menu).
Provides a mechanism to manually trigger re-renders of a component based on an external condition or state change.
Provides a convenient interface for reading, writing, and deleting cookies.
Provides a function to copy text to the user's clipboard and tracks the success or failure status.
Manages a countdown timer with start, pause, and reset controls.
Manages a numerical counter, allowing for incrementing, decrementing, and resetting.
A drop-in replacement for React.useEffect
that uses a custom comparison function for its dependencies.
Works like useMemo
but allows you to define a custom comparison function for its dependencies.
Allows you to cycle through a list of values.
Determines whether the current device is a mobile device based on screen width.
A basic hook for handling internationalization (i18n).
Runs its effect function only once, specifically when the component unmounts.
Executes a cleanup function when the component unmounts.
Functions similarly to useEffect
, but skips running the effect callback after the initial render.
Interacts with the browser's Vibration API.
A performance optimization hook for rendering long lists by only rendering visible items.
A live demo environment showcasing all hooks will be available here