🚀 A comprehensive collection of custom React hooks and utility functions
Streamline complex problem-solving within React applications with our carefully crafted hooks and utilities. Experience seamless integration, enhanced functionality, and developer-friendly APIs.
|
|
|
|
# Using npm
npm install mukul-react-hooks
# Using yarn
yarn add mukul-react-hooks
# Using pnpm
pnpm add mukul-react-hooks
import { useTimeout, useMediaQuery, lib } from "mukul-react-hooks";
function MyComponent() {
const isMobile = useMediaQuery("(max-width: 768px)");
const [startTimer] = useTimeout(() => console.log("Timer executed!"), 3000);
return (
<div>
<p>Device: {isMobile ? "Mobile" : "Desktop"}</p>
<button onClick={startTimer}>Start 3s Timer</button>
</div>
);
}
Hook | Description | Use Case |
---|---|---|
⏰ useTimeout | Execute callbacks after specified delays | Debouncing, delayed actions |
📱 useMediaQuery | Responsive design with CSS media queries | Responsive components |
⬆️ useIsTopOfPage | Detect if user is at the top of page | Scroll-based UI changes |
🖥️ useFullScreen | Manage fullscreen mode | Media players, presentations |
Warn users about unsaved changes | Forms, editors |
Execute callbacks after specified delays with easy control and cleanup
📋 API Reference
const [startTimeout, clearTimeout] = useTimeout(callback, delay);
Parameters:
callback: () => void
- Function to execute after delaydelay: number
- Delay in milliseconds
Returns:
[startTimeout, clearTimeout]
- Tuple with start and clear functions
import { useTimeout } from "mukul-react-hooks";
function DelayedMessage() {
const [startTimer] = useTimeout(() => {
alert("3 seconds have passed!");
}, 3000);
return (
<div>
<button onClick={startTimer}>Start 3s Timer</button>
</div>
);
} |
import { useTimeout } from "mukul-react-hooks";
function DelayedMessage(): JSX.Element {
const [startTimer] = useTimeout<string>((message?: string) => {
console.log(message || "Timer executed!");
}, 3000);
const handleClick = () => startTimer("Hello TypeScript!");
return (
<div>
<button onClick={handleClick}>Start 3s Timer</button>
</div>
);
} |
Responsive design made easy with CSS media query detection
📋 API Reference
const matches = useMediaQuery(query);
Parameters:
query: string
- CSS media query string
Returns:
boolean
- Whether the media query matches
import { useMediaQuery } from "mukul-react-hooks";
function ResponsiveComponent() {
const isMobile = useMediaQuery("(max-width: 768px)");
const isTablet = useMediaQuery("(min-width: 769px) and (max-width: 1024px)");
const isDesktop = useMediaQuery("(min-width: 1025px)");
return (
<div className={`layout ${isMobile ? "mobile" : isTablet ? "tablet" : "desktop"}`}>
<h2>Current Device: {isMobile ? "📱 Mobile" : isTablet ? "📟 Tablet" : "🖥️ Desktop"}</h2>
<p>Resize your window to see the magic! ✨</p>
</div>
);
}
Detect when users are at the top of the page for scroll-based UI changes
📋 API Reference
const isTop = useIsTopOfPage(threshold?);
Parameters:
threshold?: number
- Scroll threshold in pixels (default: 0)
Returns:
boolean
- Whether user is at the top of the page
import { useIsTopOfPage } from "mukul-react-hooks";
function ScrollIndicator() {
const isTop = useIsTopOfPage();
return (
<div>
<header className={`navbar ${!isTop ? "navbar-scrolled" : ""}`}>
<h1>My Website</h1>
{!isTop && <div className="scroll-indicator">📍 You've scrolled down</div>}
</header>
<main style={{ height: "200vh", padding: "2rem" }}>
<h2>Scroll down to see the navbar change! 👇</h2>
<p>Status: {isTop ? "⬆️ At the top" : "⬇️ Scrolled down"}</p>
</main>
</div>
);
}
Manage fullscreen mode with cross-browser compatibility
📋 API Reference
const { isFullscreen, toggleFullscreen, enterFullscreen, exitFullscreen } = useFullScreen();
Returns:
isFullscreen: boolean
- Current fullscreen statetoggleFullscreen: () => void
- Toggle fullscreen modeenterFullscreen: () => void
- Enter fullscreen modeexitFullscreen: () => void
- Exit fullscreen mode
import { useFullScreen } from "mukul-react-hooks";
function VideoPlayer() {
const { isFullscreen, toggleFullscreen, enterFullscreen, exitFullscreen } = useFullScreen();
return (
<div className="video-container">
<video controls width="100%" height="400">
<source src="sample-video.mp4" type="video/mp4" />
</video>
<div className="controls">
<button onClick={toggleFullscreen} className="fullscreen-btn">
{isFullscreen ? "🔲 Exit Fullscreen" : "⛶ Enter Fullscreen"}
</button>
<div className="control-group">
<button onClick={enterFullscreen}>🔍 Enter</button>
<button onClick={exitFullscreen}>🔍 Exit</button>
</div>
</div>
<p>Status: {isFullscreen ? "🖥️ Fullscreen Active" : "📱 Normal View"}</p>
</div>
);
}
Prevent accidental data loss with unsaved change warnings
📋 API Reference
useUnsavedChangeAlert(hasUnsavedChanges, message?);
Parameters:
hasUnsavedChanges: boolean
- Whether there are unsaved changesmessage?: string
- Custom warning message
Behavior:
- Shows browser confirmation dialog when leaving page
- Prevents accidental navigation away from unsaved work
import { useUnsavedChangeAlert } from "mukul-react-hooks";
import { useState } from "react";
function FormEditor() {
const [formData, setFormData] = useState({ name: "", email: "" });
const [originalData] = useState({ name: "", email: "" });
// Check if form has unsaved changes
const hasUnsavedChanges = JSON.stringify(formData) !== JSON.stringify(originalData);
// Show warning when leaving page with unsaved changes
useUnsavedChangeAlert(
hasUnsavedChanges,
"You have unsaved changes. Are you sure you want to leave?"
);
return (
<form>
<div>
<label>Name:</label>
<input
value={formData.name}
onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
/>
</div>
<div>
<label>Email:</label>
<input
value={formData.email}
onChange={(e) => setFormData((prev) => ({ ...prev, email: e.target.value }))}
/>
</div>
<div className="status">
{hasUnsavedChanges ? "⚠️ Unsaved changes" : "✅ All changes saved"}
</div>
<button type="submit">Save Changes</button>
</form>
);
}
A comprehensive collection of utility functions with full TypeScript support
Category | Functions | Description |
---|---|---|
🔤 String Utils | transformString , truncateStringEnd , truncateStringMiddle |
String manipulation and formatting |
🔢 Number Utils | numberFormatWithCommas , internationalCurrencyConvert |
Number formatting and currency conversion |
📧 Validation | isValidEmail , isEmptyObject |
Data validation utilities |
🎨 Generators | randomColor , generateUniqueId |
Random value generators |
📁 File Utils | downloadString |
File download utilities |
⏱️ Async Utils | asyncDelay , waitSomeMoment |
Async operation helpers |
📋 Array Utils | arrayToCommaSeparatedText |
Array manipulation |
📅 Date Utils | unixToDateTime |
Date and time utilities |
import { lib } from "mukul-react-hooks";
const {
arrayToCommaSeparatedText,
randomColor,
isValidEmail,
numberFormatWithCommas,
downloadString,
} = lib;
function UtilityDemo() {
const handleDemo = () => {
// String and array utilities
console.log(arrayToCommaSeparatedText(["React", "Vue", "Angular"]));
// → "React, Vue, Angular"
// Validation
console.log(isValidEmail("user@example.com"));
// → true
// Number formatting
console.log(numberFormatWithCommas(1234567));
// → "1,234,567"
// Generate random color
console.log(randomColor());
// → "#ff6b35"
};
return (
<div>
<button onClick={handleDemo}>Run Demo</button>
<button onClick={() => downloadString("Hello World!", "demo", "txt")}>
📥 Download File
</button>
</div>
);
} |
import { lib } from "mukul-react-hooks";
const {
generateUniqueId,
internationalCurrencyConvert,
truncateStringEnd,
unixToDateTime,
asyncDelay,
} = lib;
async function TypeSafeDemo(): Promise<JSX.Element> {
// Type-safe function calls
const uniqueId: string = generateUniqueId();
const currency: string | number = internationalCurrencyConvert(1500000);
const truncated: string = truncateStringEnd("Long text here", 10);
const dateTime: string = unixToDateTime(Date.now() / 1000);
// Async operations with proper typing
await asyncDelay(1000);
const handleAsyncAction = async (): Promise<void> => {
await asyncDelay(2000);
console.log("Action completed!");
};
return (
<div>
<p>ID: {uniqueId}</p>
<p>Currency: {currency}</p>
<p>Truncated: {truncated}</p>
<p>DateTime: {dateTime}</p>
<button onClick={handleAsyncAction}>⏳ Async Action</button>
</div>
);
} |
🔍 Click to expand full API documentation
// String utilities
transformString(text: string): string // Convert to snake_case
truncateStringEnd(text: string, length: number): string // Truncate with "..."
truncateStringMiddle(text: string, length: number, separator: string): string
// Number utilities
numberFormatWithCommas(number: number): string // Add thousand separators
internationalCurrencyConvert(amount: number): string | number // Convert to K, M, B format
// Validation utilities
isValidEmail(email: string): boolean // Email validation
isEmptyObject(obj: object): boolean // Check if object is empty
// Generator utilities
randomColor(): string // Generate random hex color
generateUniqueId(): string // Generate unique identifier
// File utilities
downloadString(content: string, filename: string, extension: string): void
// Async utilities
asyncDelay(ms: number): Promise<void> // Promise-based delay
waitSomeMoment(ms: number): Promise<void> // Alternative delay function
// Array utilities
arrayToCommaSeparatedText(array: string[]): string // Join array with commas
// Date utilities
unixToDateTime(timestamp: number): string // Convert Unix timestamp to readable date
We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Resource | Link | Description |
---|---|---|
📖 Live Documentation | mukul-react-hooks.vercel.app | Interactive docs & test suite |
📦 NPM Package | npmjs.com/package/mukul-react-hooks | Official package page |
🐙 GitHub Repository | github.com/SamiurRahmanMukul/mukul-react-hooks | Source code & issues |
🐛 Bug Reports | GitHub Issues | Report bugs & request features |
This project is licensed under the MIT License - see the LICENSE.txt file for details.
Made with ❤️ by Mukul