react-hookman v1.0.0
Generated by AI
React Hookman
A collection of reusable and type-safe React hooks to simplify your development workflow.
Installation
npm install react-hookman
or
yarn add react-hookman
Available 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 totrue
setFalse()
: Sets the state tofalse
toggle()
: 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
mousedown
event 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
execCommand
if 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: absolute
style - 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
-true
if 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>
);
}