react-custom-hook-library v1.0.4
React-Custom-hooks-Library
A comprehensive collection of production-ready, TypeScript-enabled React hooks designed to accelerate modern web application development. These hooks are built with performance, reusability, and developer experience in mind.
🚀 Features
- 📦 12+ Production-Ready Hooks
- 💪 Full TypeScript Support
- 📚 Comprehensive Documentation
- 📱 Mobile-Friendly
- 🔄 Regular Updates
📦 Installation
Choose your preferred package manager:
# Using npm
npm install npm i react-custom-hook-library
# Using yarn
yarn add npm i react-custom-hook-library
# Using pnpm
pnpm add npm i react-custom-hook-library
🎯 Quick Start
import { useToggle, useLocalStorage } from 'react-custom-hook-library';
function App() {
const [isEnabled, toggle] = useToggle(false);
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={toggle}>
Toggle {isEnabled ? 'On' : 'Off'}
</button>
);
}
📚 Available Hooks
Hook Name | Description | Use Case |
---|---|---|
useClickOutside | Detect clicks outside elements | Modals, dropdowns, menus |
useClipboard | Clipboard operations | Copy/paste functionality |
useDebounce | Delay value updates | Search inputs, API calls |
useFetch | Data fetching with cache | API integration |
useForm | Form state management | User input forms |
useHistory | Track value history | Undo/redo functionality |
useInfiniteScroll | Infinite scrolling | Social media feeds |
useKeyPress | Keyboard event handling | Shortcuts, games |
useLocalStorage | Local storage state | User preferences |
useMediaQuery | Media query detection | Responsive designs |
usePagination | Pagination logic | Data tables |
useToggle | Boolean state toggle | Switches, accordions |
Usage Examples
1. useClickOutside
A modal that closes when clicking outside, perfect for photo galleries or menus.
import { useClickOutside } from 'react-custom-hook-library';
const PhotoViewer = () => {
const [isOpen, setIsOpen] = useState(false);
const modalRef = useClickOutside(() => setIsOpen(false));
return (
<div>
<button onClick={() => setIsOpen(true)}>
View Holiday Photos 📸
</button>
{isOpen && (
<div className="modal-overlay">
<div ref={modalRef} className="modal-content">
<img src="vacation.jpg" alt="Holiday" />
<p>Click outside to close</p>
</div>
</div>
)}
</div>
);
};
2. useClipboard
A component that helps share color palettes between designers.
import { useClipboard } from 'react-custom-hook-library';
const ColorPalette = () => {
const { copy, copiedText } = useClipboard();
const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1'];
return (
<div className="color-palette">
{colors.map(color => (
<div
key={color}
style={{ backgroundColor: color }}
onClick={() => copy(color)}
>
{copiedText === color ? '✓ Copied!' : color}
</div>
))}
</div>
);
};
3. useDebounce
A smart search component that reduces API calls.
import { useDebounce } from 'react-custom-hook-library';
const SmartSearch = () => {
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 500);
const [results, setResults] = useState([]);
useEffect(() => {
if (debouncedSearch) {
// Simulate API call
console.log(`Searching for: ${debouncedSearch}`);
}
}, [debouncedSearch]);
return (
<div>
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search movies..."
/>
<div>Searching: {debouncedSearch}</div>
</div>
);
};
4. useFetch
A weather dashboard that caches responses.
import { useFetch } from 'react-custom-hook-library';
const WeatherDashboard = ({ city }) => {
const { data, loading, error, refetch } = useFetch<WeatherData>(
`https://api.weather.com/${city}`
);
return (
<div className="weather-card">
{loading && <div>☁️ Loading weather...</div>}
{error && <div>❌ Failed to load weather</div>}
{data && (
<>
<h2>{data.temperature}°C in {city}</h2>
<button onClick={refetch}>🔄 Refresh</button>
</>
)}
</div>
);
};
5. useForm
A dynamic pizza order form.
import { useForm } from 'react-custom-hook-library';
const PizzaOrderForm = () => {
const { values, handleChange, reset } = useForm({
size: 'medium',
toppings: '',
extra_cheese: false,
delivery_notes: ''
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log('Order placed:', values);
reset();
};
return (
<form onSubmit={handleSubmit}>
<select name="size" value={values.size} onChange={handleChange}>
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
<input
name="toppings"
placeholder="Toppings"
value={values.toppings}
onChange={handleChange}
/>
<button type="submit">🍕 Order Now</button>
</form>
);
};
6. useHistory
A drawing app that implements undo functionality.
import { useHistory } from 'react-custom-hook-library';
const SimpleDrawingApp = () => {
const [currentStroke, setCurrentStroke] = useState([]);
const strokeHistory = useHistory(currentStroke);
const addPoint = (e) => {
const point = { x: e.clientX, y: e.clientY };
setCurrentStroke([...currentStroke, point]);
};
return (
<div>
<canvas onClick={addPoint} />
<div>
Points: {currentStroke.length}
History States: {strokeHistory.length}
</div>
</div>
);
};
7. useInfiniteScroll
A social media feed with infinite scrolling.
import { useInfiniteScroll } from 'react-custom-hook-library';
const PhotoFeed = () => {
const [posts, setPosts] = useState([]);
const isFetching = useInfiniteScroll(loadMorePosts);
function loadMorePosts() {
// Simulate loading more posts
setTimeout(() => {
setPosts(prev => [...prev, ...generateNewPosts()]);
}, 1000);
}
return (
<div className="feed">
{posts.map(post => (
<div key={post.id} className="post">
{post.content}
</div>
))}
{isFetching && <div>📜 Loading more...</div>}
</div>
);
};
8. useKeyPress
A simple piano app that responds to keyboard input.
import { useKeyPress } from 'react-custom-hook-library';
const SimplePiano = () => {
const [lastNote, setLastNote] = useState('');
useKeyPress('a', () => playNote('C'));
useKeyPress('s', () => playNote('D'));
useKeyPress('d', () => playNote('E'));
useKeyPress('f', () => playNote('F'));
const playNote = (note) => {
setLastNote(note);
// Add sound playing logic here
};
return (
<div className="piano">
<div>Last Note Played: {lastNote}</div>
<div className="keys">
<div>A = C</div>
<div>S = D</div>
<div>D = E</div>
<div>F = F</div>
</div>
</div>
);
};
9. useLocalStorage
A theme switcher that remembers user preference.
import { useLocalStorage } from 'react-custom-hook-library';
const ThemeSwitcher = () => {
const [theme, setTheme] = useLocalStorage('theme', 'light');
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<div className={`app ${theme}`}>
<button onClick={toggleTheme}>
{theme === 'light' ? '🌙' : '☀️'}
</button>
<p>Current theme: {theme}</p>
</div>
);
};
10. useMediaQuery
A responsive navigation menu.
import { useMediaQuery } from 'react-custom-hook-library';
const ResponsiveNav = () => {
const isMobile = useMediaQuery('(max-width: 768px)');
return (
<nav>
{isMobile ? (
<button>📱 Menu</button>
) : (
<div className="desktop-nav">
<a href="/home">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</div>
)}
</nav>
);
};
11. usePagination
A paginated recipe book.
import { usePagination } from 'react-custom-hook-library';
const RecipeBook = () => {
const recipes = [/* ... array of recipes ... */];
const {
currentItems: currentRecipes,
currentPage,
totalPages,
nextPage,
prevPage
} = usePagination(recipes, 3);
return (
<div className="recipe-book">
<h1>📖 My Recipes (Page {currentPage}/{totalPages})</h1>
{currentRecipes.map(recipe => (
<div key={recipe.id} className="recipe-card">
<h3>{recipe.title}</h3>
<p>{recipe.description}</p>
</div>
))}
<div className="pagination">
<button onClick={prevPage}>👈 Previous</button>
<button onClick={nextPage}>Next 👉</button>
</div>
</div>
);
};
12. useToggle
A fun flashcard component for learning.
import { useToggle } from 'react-custom-hook-library';
const Flashcard = ({ question, answer }) => {
const [isFlipped, toggle] = useToggle(false);
return (
<div
className={`flashcard ${isFlipped ? 'flipped' : ''}`}
onClick={toggle}
>
<div className="front">
<h3>Question:</h3>
{question}
</div>
<div className="back">
<h3>Answer:</h3>
{answer}
</div>
<div className="helper-text">
{isFlipped ? '🔄 Click to hide answer' : '🤔 Click to reveal'}
</div>
</div>
);
};
Each example demonstrates a practical, real-world use case while keeping the code simple and focused. These components can be used as starting points and customized based on specific needs.
Remember to add appropriate styling and error handling in production applications. Also, some examples assume the existence of certain styles or additional logic that would need to be implemented in a real application.
🔍 TypeScript Support
All hooks are written in TypeScript and include comprehensive type definitions:
import { useForm } from 'react-custom-hooks';
interface UserForm {
name: string;
email: string;
age: number;
}
const { values, errors } = useForm<UserForm>({
initialValues: {
name: '',
email: '',
age: 0
}
});
📈 Performance Considerations
- All hooks are memoized using
useMemo
anduseCallback
where appropriate - Batch updates are utilized to prevent unnecessary re-renders
- Built-in debouncing and throttling for performance-critical operations
📝 Contributing
We love your input! We want to make contributing as easy and transparent as possible, whether it's:
- Reporting a bug
- Discussing the current state of the code
- Submitting a fix
- Proposing new features
- Becoming a maintainer
Development Process
- Fork the repo
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
📄 License
This project is licensed under the MIT License.
💖 Support
If you find this project helpful, please consider:
- Giving it a ⭐️ on GitHub
- Sharing it with friends and colleagues
📮 Contact
- Website: portfolio
- Email: sanjayrahul6787@gmail.com
Made with ❤️ by Sanjayrahul