A collection of reusable and type-safe React hooks to simplify your development workflow.
npm install react-hookman###### Generated by AI
``bash`
npm install react-hookman
`bash`
yarn add react-hookman
---
---
A hook for managing boolean state with utility functions.
(optional) โ Initial state, defaults to falseReturns
- value: Current boolean state
- setValue(value: boolean): Sets the state to a specific value
- setTrue(): Sets the state to true
- setFalse(): Sets the state to false
- toggle(): Toggles the current state๐ง Usage
`tsx
const { value, setTrue, setFalse, toggle } = useBoolean(false);
return (
useBoolean Hook Demo
Current value: {value.toString()}
{value && (
style={{
marginTop: "20px",
padding: "20px",
backgroundColor: "#e0e0e0",
}}
>
This content is visible when value is true!
)}
๐ฏ useClickOutside ๐ฑ๏ธ
React hook that detects clicks outside a specified element and triggers a callback.
Parameters
- ref: RefObject - Reference to the target HTML element
- cb: () => void - Callback function triggered on outside clicksReturns
- voidType Parameters
- T extends HTMLElement - Type of the referenced HTML elementNotes
- Automatically cleans up event listeners on unmount
- Attaches to mousedown event on document
- Safe to use with null refs๐ง Usage
`tsx
const Modal: React.FC = () => {
const [isOpen, setIsOpen] = useState(false);
const modalRef = useRef(null); useClickOutside(modalRef as React.RefObject, () =>
setIsOpen(false)
);
return (
{isOpen && (
style={{
position: "fixed",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
padding: "20px",
background: "white",
boxShadow: "0px 4px 10px rgba(0,0,0,0.1)",
borderRadius: "8px",
}}
ref={modalRef}
>
This is a modal. Click outside to close.
)}
๐
useClipboard HookA React hook for copying text to the clipboard with both Clipboard API and fallback support. It also provides a
copied state to track copy status.---
Returns
- copied: boolean - Indicates if text was recently copied
- copyToClipboard(text: string): Promise - Copies text to clipboardFeatures
- Uses modern Clipboard API with fallback
- Auto-resets copy status after 2 seconds
- Handles errors gracefully
- Works in all modern browsersNotes
- Copy status resets automatically after 2000ms
- Falls back to execCommand if Clipboard API unavailable
- Logs errors to console if copy fails
๐ง Usage
`tsx
import React, { useState } from "react";
import { useClipboard } from "./useClipboard";const ClipboardExample: React.FC = () => {
const { copied, copyToClipboard } = useClipboard();
const [text, setText] = useState("Hello, World!");
return (
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text to copy"
/>
);
};export default ClipboardExample;
`โณ
useDebounce HookA React hook for debouncing values. It delays updating the state until after a specified time has passed since the last change.
---
๐ง Usage
`tsx
import React, { useState } from "react";
import { useDebounce } from "./useDebounce";const DebounceExample: React.FC = () => {
const [text, setText] = useState("");
const debouncedText = useDebounce(text, 500);
return (
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
Debounced Value: {debouncedText}
);
};export default DebounceExample;
`๐ API
useDebounceReturns the debounced value after the specified delay.
| Parameter | Type | Default | Description |
| --------- | ------ | ------- | ---------------------------------------------- |
| value | T | โ | The value to debounce. |
| delay | number | 500 | The debounce delay in milliseconds (optional). |
๐
useDestroy HookA React hook that runs a cleanup function when a component unmounts. Useful for handling cleanup logic like removing event listeners, aborting requests, or clearing intervals.
---
๐ง Usage
`tsx
import React, { useState } from "react";
import { useDestroy } from "./useDestroy";const DestroyExample: React.FC = () => {
const [visible, setVisible] = useState(true);
return (
{visible && }
);
};const ChildComponent: React.FC = () => {
useDestroy(() => {
console.log("Component unmounted! Cleanup logic here.");
});
return
This component will trigger cleanup on unmount.
;
};export default DestroyExample;
`๐ API
useDestroy(func: () => void)Runs the provided function when the component unmounts.
| Parameter | Type | Description |
| --------- | ---------- | --------------------------------------------------- |
| func | () => void | The function to execute when the component unmounts |
๐ useDragAndDrop ๐ฑ๏ธ
React hook for adding drag and drop functionality to elements.
Usage
`typescript
function App() {
const [ref, isDragging] = useDragAndDrop(); // Explicitly type the ref return (
ref={ref}
style={{
position: "absolute",
backgroundColor: "lightblue",
padding: "10px",
cursor: isDragging ? "grabbing" : "grab",
}}
>
Drag me!
`
- Reference to attach to draggable element
- isDragging: boolean - Current drag stateType Parameters
- T extends HTMLElement - Type of the draggable elementNotes
- Element must have position: absolute style
- Handles mouse events automatically
- Cleans up event listeners on unmount
- Updates element position in real-time
- Tracks offset from click position๐
useFetch HookA custom React hook for fetching data asynchronously with built-in support for loading state, error handling, retries, and aborting requests.
---
๐ Installation
This is a standalone hook. You can directly copy and use it in your React project.
---
๐ง Usage
`tsx
import React, { useState } from "react";
import { useFetch } from "./useFetch";const FetchExample: React.FC = () => {
const [url, setUrl] = useState(
"https://jsonplaceholder.typicode.com/posts/1"
);
const { data, loading, error, retry } = useFetch<{
title: string;
body: string;
}>(url);
return (
Fetch Example
{loading && Loading...
}
{error && Error: {error.message}
}
{data && (
{data.title}
{data.body}
)}
onClick={() => setUrl("https://jsonplaceholder.typicode.com/posts/2")}
>
Fetch Another Post
);
};export default FetchExample;
`๐ API
$3
#### Parameters
| Parameter | Type | Description |
| --------- | ------------ | ------------------------------------------------- |
| url | string | The API endpoint to fetch data from |
| options | FetchOptions | Fetch configuration (headers, method, body, etc.) |
#### FetchOptions (Extends RequestInit)
| Option | Type | Default | Description |
| ------- | ------- | ------- | -------------------------------- |
| enabled | boolean | true | If false, prevents auto-fetching |
#### Return Values
| Property | Type | Description |
| -------- | ------------- | ----------------------------------------- |
| data | T \| null | The fetched data. Defaults to null |
| loading | boolean | true while fetching, false when complete |
| error | Error \| null | Contains error details if the fetch fails |
| retry | () => void | A function to manually retry the request |
๐ฑ๏ธ
useHover HookA custom React hook that detects whether an element is being hovered over. It returns a boolean value indicating the hover state.
---
๐ง Usage
`tsx
import { useRef } from "react";
import { useHover } from "./useHover";function Component() {
const ref = useRef(null);
const isHovered = useHover(ref);
return (
ref={ref}
style={{ backgroundColor: isHovered ? "lightblue" : "white" }}
>
Hover over me!
๐ API
$3
#### Parameters
| Parameter | Type | Description |
| --------- | ------------ | ----------- | ---------------------------------------------- |
| ref | RefObject | null | A React ref object pointing to an HTMLElement. |
#### Return Value
| Type | Description |
|---------------|------------------------------------------------------|
|
boolean | true if the element is hovered, false otherwise. |
| Type Parameters | T extends HTMLElement \| null: The type of element the ref refers to (automatically inferred). |โ useIdle ๐ค
React hook that detects user inactivity after a specified timeout.
Parameters
- timeout: number - Inactivity duration in milliseconds (default: 30000)Returns
- isIdle: boolean - Current idle stateFeatures
- Monitors common user interactions:
- Mouse movement
- Keyboard activity
- Scrolling
- Clicks
- Touch events
- Automatically resets timer on activity
- Safe for server-side rendering
- Cleans up listeners on unmountUsage
`typescript
function App() {
const isIdle = useIdle(10000); // return (
{isIdle ? "System idle โณ" : "Active ๐ป"}
);
`
๐ useLongPress ๐
React hook for detecting long press interactions on elements, supporting both mouse and touch events.
Parameters
-
callback: (event: PressEvent, position: Position) => void - Function called when long press is detected
- options: LongPressOptions - Configuration options object$3
`typescript
interface LongPressOptions {
threshold?: number; // Duration before triggering (ms), default: 400
moveThreshold?: number; // Maximum movement allowed (px), default: 10
preventDefault?: boolean; // Prevent default events, default: true
disabled?: boolean; // Disable the hook, default: false
onStart?: (event: PressEvent, position: Position) => void;
onFinish?: (event: PressEvent, position: Position, duration: number) => void;
onCancel?: (event: PressEvent, position: Position) => void;
onMove?: (event: PressEvent, position: Position) => void;
}
`Returns
Object containing event handlers to spread onto the target element:
`typescript
interface LongPressHandlers {
onMouseDown: (event: React.MouseEvent) => void;
onMouseUp: (event: React.MouseEvent) => void;
onMouseLeave: (event: React.MouseEvent) => void;
onMouseMove: (event: React.MouseEvent) => void;
onTouchStart: (event: React.TouchEvent) => void;
onTouchEnd: (event: React.TouchEvent) => void;
onTouchMove: (event: React.TouchEvent) => void;
}
`
Features
- ๐ฑ๏ธ Supports both mouse and touch events
- ๐ Configurable movement threshold
- โฑ๏ธ Adjustable timing threshold
- ๐ซ Cancel on movement exceeding threshold
- ๐ Provides position information
- โฟ Accessibility through event prevention control
- ๐ Lifecycle callbacks for press states
Notes
- Long press is triggered after holding for the specified threshold duration
- Cancels if movement exceeds moveThreshold
- Provides position coordinates for all events
- Cleans up timers automatically
- Can be disabled dynamically
- Supports custom callbacks for different press states
๐ฑ useMobile ๐
React hook for detecting mobile viewport width with debounced updates.
Returns
- boolean - true if viewport width is less than 768px (mobile breakpoint)Usage
`typescript
function App() {
const isMobile = useMobile(); return (
{isMobile ? "Mobile View!" : "Desktop View!"}
);
}
`
๐ฑ๏ธ useMousePosition ๐
React hook for tracking mouse position globally and relative to a specific element.
Returns
- position: Position - Object containing all position coordinates
- ref: React.Ref - Reference to attach to tracked element
Position Object
`typescript
interface Position {
x: number; // Global mouse X position
y: number; // Global mouse Y position
elementX?: number; // Mouse X position relative to element
elementY?: number; // Mouse Y position relative to element
elementPositionX?: number; // Element's X position on page
elementPositionY?: number; // Element's Y position on page
}
`Type Parameters
-
T extends HTMLElement - Type of the element to trackFeatures
- ๐ Tracks global mouse position
- ๐ Provides element-relative coordinates
- ๐ Calculates element position on page
- ๐ Real-time updates
- ๐งน Automatic cleanup of event listeners
- ๐ช TypeScript supportUsage
`typescriptfunction MouseTracker() {
const [position, ref] = useMousePosition();
return (
{position.elementX !== undefined && (
style={{
position: "absolute",
left: position.elementX,
top: position.elementY,
width: "10px",
height: "10px",
background: "red",
borderRadius: "50%",
transform: "translate(-50%, -50%)",
}}
/>
)}
);
}`
๐ useOnlineStatus ๐ถ
React hook for monitoring the user's internet connection status in real-time.
Returns
-
boolean - Current online status
- true - User is online
- false - User is offlineFeatures
- ๐ Real-time connection monitoring
- ๐ Browser-compatible checks
- ๐ Automatic event handling
- ๐งน Cleanup on unmount
- ๐ฏ SSR-friendly
- โก Zero configurationUsage
`typescript
function App() {
const isOnline = useOnlineStatus(); return (
Network Status
You are currently{" "}
{isOnline ? "Online" : "Offline"}
.
);
}
`
๐ usePageTitle ๐ค
React hook for dynamically managing the document title with automatic cleanup.
Parameters
-
title: string - The new title to set for the documentUsage
`typescript
function App() {
usePageTitle("My Awesome Page"); return (
My Awesome Page
{/ Your content /}
);
}
`
๐ useScrollPosition ๐
React hook for tracking window scroll position with performance optimization.
Returns
- number - Current vertical scroll position in pixels
Usage
`typescript
function App() {
const scrollPosition = useScrollPosition(); return (
position: "fixed",
backgroundColor: scrollPosition > 100 ? "#fff" : "transparent"
}}>
Scrolled: {scrollPosition}px
{/ Your content /}
);
}
`
๐ useToggle ๐๏ธ
React hook for managing boolean state with a simple toggle function.
Parameters
- initialValue?: boolean - Initial state value (default: false)Returns
`typescript
[boolean, () => void]
`Usage
`typescript
function App() {
const [isOn, toggle] = useToggle(false);
return (
{isOn ? "ON" : "OFF"}
);
}
`
โ๏ธ useTruncate ๐
React hook for truncating text strings with ellipsis.
Returns
` typescript
{
truncate: (text: string, length: number) => string
}
`
Parameters for truncate function
-
text: string - Text to truncate (default: '')
- length: number - Maximum length before truncation (default: 0)Usage
`typescript
function MessagePreview() {
const { truncate } = useTruncate();
return (
{truncate("Sender Name", 10)}
{truncate("This is the message content", 25)}
);
}
`
๐ฅ๏ธ useWindowSize ๐
React hook for tracking browser window dimensions with real-time updates.
Returns
`typescript
{
width: number, // Current window width in pixels
height: number // Current window height in pixels
}
`
Usage
`typescript
function App() {
const { width, height } = useWindowSize(); return (
Window Width: {width}px
Window Height: {height}px
);
}
``