react-hookman
v1.0.0
Published
A collection of reusable and type-safe React hooks to simplify your development workflow.
Downloads
8
Maintainers
Readme

Generated by AI
React Hookman
A collection of reusable and type-safe React hooks to simplify your development workflow.
Installation
npm install react-hookmanor
yarn add react-hookmanAvailable Hooks
useBoolean
useClickOutside
useClipboard
useDebounce
useDestroy
useDragNDrop
useFetch
useHover
useMousePosition
useIdle
useLongPress
useMobile
useMousePosition
useOnlineStatus
usePageTitle
useScrollPosition
useToggle
useTruncate
~~useUpdateEffect~~
useWindowSize
🔄 useBoolean 🎛️
A hook for managing boolean state with utility functions.
Parameters
initialValue: boolean(optional) – Initial state, defaults tofalse
Returns
value: Current boolean statesetValue(value: boolean): Sets the state to a specific valuesetTrue(): Sets the state totruesetFalse(): Sets the state tofalsetoggle(): Toggles the current state
🔧 Usage
const { value, setTrue, setFalse, toggle } = useBoolean(false);
return (
<div style={{ padding: "20px" }}>
<h2>useBoolean Hook Demo</h2>
<div style={{ marginBottom: "20px" }}>
<p>Current value: {value.toString()}</p>
</div>
<div style={{ display: "flex", gap: "10px" }}>
<button onClick={toggle}>Toggle</button>
<button onClick={setTrue}>Set True</button>
<button onClick={setFalse}>Set False</button>
</div>
{value && (
<div
style={{
marginTop: "20px",
padding: "20px",
backgroundColor: "#e0e0e0",
}}
>
This content is visible when value is true!
</div>
)}
</div>
);🎯 useClickOutside 🖱️
React hook that detects clicks outside a specified element and triggers a callback.
Parameters
ref: RefObject<T>- Reference to the target HTML elementcb: () => void- Callback function triggered on outside clicks
Returns
void
Type Parameters
T extends HTMLElement- Type of the referenced HTML element
Notes
- Automatically cleans up event listeners on unmount
- Attaches to
mousedownevent on document - Safe to use with null refs
🔧 Usage
const Modal: React.FC = () => {
const [isOpen, setIsOpen] = useState(false);
const modalRef = useRef<HTMLDivElement | null>(null);
useClickOutside(modalRef as React.RefObject<HTMLElement>, () =>
setIsOpen(false)
);
return (
<div>
<button onClick={() => setIsOpen(true)}>Open Modal</button>
{isOpen && (
<div
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}
>
<p>This is a modal. Click outside to close.</p>
</div>
)}
</div>
);
};📋 useClipboard Hook
A 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 copiedcopyToClipboard(text: string): Promise<void>- Copies text to clipboard
Features
- Uses modern Clipboard API with fallback
- Auto-resets copy status after 2 seconds
- Handles errors gracefully
- Works in all modern browsers
Notes
- Copy status resets automatically after 2000ms
- Falls back to
execCommandif Clipboard API unavailable - Logs errors to console if copy fails
🔧 Usage
import React, { useState } from "react";
import { useClipboard } from "./useClipboard";
const ClipboardExample: React.FC = () => {
const { copied, copyToClipboard } = useClipboard();
const [text, setText] = useState("Hello, World!");
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text to copy"
/>
<button onClick={() => copyToClipboard(text)}>
{copied ? "Copied!" : "Copy to Clipboard"}
</button>
</div>
);
};
export default ClipboardExample;⏳ useDebounce Hook
A React hook for debouncing values. It delays updating the state until after a specified time has passed since the last change.
🔧 Usage
import React, { useState } from "react";
import { useDebounce } from "./useDebounce";
const DebounceExample: React.FC = () => {
const [text, setText] = useState("");
const debouncedText = useDebounce(text, 500);
return (
<div>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
<p>Debounced Value: {debouncedText}</p>
</div>
);
};
export default DebounceExample;🛠 API
useDebounce<T>(value: T, delay?: number): T
Returns 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 Hook
A 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
import React, { useState } from "react";
import { useDestroy } from "./useDestroy";
const DestroyExample: React.FC = () => {
const [visible, setVisible] = useState(true);
return (
<div>
<button onClick={() => setVisible(!visible)}>
{visible ? "Unmount Component" : "Mount Component"}
</button>
{visible && <ChildComponent />}
</div>
);
};
const ChildComponent: React.FC = () => {
useDestroy(() => {
console.log("Component unmounted! Cleanup logic here.");
});
return <p>This component will trigger cleanup on unmount.</p>;
};
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
function App() {
const [ref, isDragging] = useDragAndDrop<HTMLDivElement>(); // Explicitly type the ref
return (
<div
ref={ref}
style={{
position: "absolute",
backgroundColor: "lightblue",
padding: "10px",
cursor: isDragging ? "grabbing" : "grab",
}}
>
Drag me!
</div>
);
Returns
elementRef: RefObject<T>- Reference to attach to draggable elementisDragging: boolean- Current drag state
Type Parameters
T extends HTMLElement- Type of the draggable element
Notes
- Element must have
position: absolutestyle - Handles mouse events automatically
- Cleans up event listeners on unmount
- Updates element position in real-time
- Tracks offset from click position
🌐 useFetch Hook
A 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
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 (
<div>
<h2>Fetch Example</h2>
{loading && <p>Loading...</p>}
{error && <p>Error: {error.message}</p>}
{data && (
<div>
<h3>{data.title}</h3>
<p>{data.body}</p>
</div>
)}
<button onClick={retry}>Retry</button>
<button
onClick={() => setUrl("https://jsonplaceholder.typicode.com/posts/2")}
>
Fetch Another Post
</button>
</div>
);
};
export default FetchExample;🛠 API
useFetch<T>(url: string, options?: FetchOptions): UseFetchReturn<T>
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 Hook
A custom React hook that detects whether an element is being hovered over. It returns a boolean value indicating the hover state.
🔧 Usage
import { useRef } from "react";
import { useHover } from "./useHover";
function Component() {
const ref = useRef<HTMLDivElement>(null);
const isHovered = useHover(ref);
return (
<div
ref={ref}
style={{ backgroundColor: isHovered ? "lightblue" : "white" }}
>
Hover over me!
</div>
);
}🛠 API
useHover<T extends HTMLElement | null>(ref: RefObject<T> | null): boolean
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 state
Features
- 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 unmount
Usage
function App() {
const isIdle = useIdle(10000); //
return (
<div style={{ color: isIdle ? "gray" : "green" }}>
{isIdle ? "System idle ⏳" : "Active 💻"}
</div>
);👆 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 detectedoptions: LongPressOptions- Configuration options object
Options
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:
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-trueif viewport width is less than 768px (mobile breakpoint)
Usage
function App() {
const isMobile = useMobile();
return (
<div>
{isMobile ? "Mobile View!" : "Desktop View!"}
</div>
);
}🖱️ useMousePosition 📍
React hook for tracking mouse position globally and relative to a specific element.
Returns
position: Position- Object containing all position coordinatesref: React.Ref<T>- Reference to attach to tracked element
Position Object
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 track
Features
- 🌐 Tracks global mouse position
- 📍 Provides element-relative coordinates
- 📐 Calculates element position on page
- 🔄 Real-time updates
- 🧹 Automatic cleanup of event listeners
- 💪 TypeScript support
Usage
function MouseTracker() {
const [position, ref] = useMousePosition<HTMLDivElement>();
return (
<div ref={ref}>
{position.elementX !== undefined && (
<div
style={{
position: "absolute",
left: position.elementX,
top: position.elementY,
width: "10px",
height: "10px",
background: "red",
borderRadius: "50%",
transform: "translate(-50%, -50%)",
}}
/>
)}
</div>
);
}
🌐 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 offline
Features
- 🔄 Real-time connection monitoring
- 🌐 Browser-compatible checks
- 🔌 Automatic event handling
- 🧹 Cleanup on unmount
- 🎯 SSR-friendly
- ⚡ Zero configuration
Usage
function App() {
const isOnline = useOnlineStatus();
return (
<div style={{ padding: "2rem", fontFamily: "sans-serif" }}>
<h1>Network Status</h1>
<p>
You are currently{" "}
<span style={{ fontWeight: "bold", color: isOnline ? "green" : "red" }}>
{isOnline ? "Online" : "Offline"}
</span>
.
</p>
</div>
);
}📑 usePageTitle 🔤
React hook for dynamically managing the document title with automatic cleanup.
Parameters
title: string- The new title to set for the document
Usage
function App() {
usePageTitle("My Awesome Page");
return (
<div>
<h1>My Awesome Page</h1>
{/* Your content */}
</div>
);
}📜 useScrollPosition 🔝
React hook for tracking window scroll position with performance optimization.
Returns
number- Current vertical scroll position in pixels
Usage
function App() {
const scrollPosition = useScrollPosition();
return (
<div>
<header style={{
position: "fixed",
backgroundColor: scrollPosition > 100 ? "#fff" : "transparent"
}}>
Scrolled: {scrollPosition}px
</header>
<main>
{/* Your content */}
</main>
</div>
);
}🔄 useToggle 🎚️
React hook for managing boolean state with a simple toggle function.
Parameters
initialValue?: boolean- Initial state value (default:false)
Returns
[boolean, () => void]Usage
function App() {
const [isOn, toggle] = useToggle(false);
return (
<div>
<p>{isOn ? "ON" : "OFF"}</p>
<button onClick={toggle}>Toggle</button>
</div>
);
}✂️ useTruncate 📝
React hook for truncating text strings with ellipsis.
Returns
{
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
function MessagePreview() {
const { truncate } = useTruncate();
return (
<div className="message">
<strong>{truncate("Sender Name", 10)}</strong>
<p>{truncate("This is the message content", 25)}</p>
</div>
);
}🖥️ useWindowSize 📐
React hook for tracking browser window dimensions with real-time updates.
Returns
{
width: number, // Current window width in pixels
height: number // Current window height in pixels
}Usage
function App() {
const { width, height } = useWindowSize();
return (
<div>
<p>Window Width: {width}px</p>
<p>Window Height: {height}px</p>
</div>
);
}