@omarstahi/react-useful-hooks
v1.0.4
Published
A collection of reusable React hooks
Readme
@omar/react-useful-hooks
A collection of reusable, production-ready React hooks written in TypeScript.
Installation
npm install @omarstahi/react-useful-hooksUsage
useDebounce
Debounces a changing value.
import { useState } from 'react';
import { useDebounce } from '@omarstahi/react-useful-hooks';
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearchTerm = useDebounce(searchTerm, 500);
// Effect will only run 500ms after the last change to searchTerm
useEffect(() => {
if (debouncedSearchTerm) {
// Perform search
}
}, [debouncedSearchTerm]);
return <input onChange={(e) => setSearchTerm(e.target.value)} />;
}useLocalStorage
Persists state to localStorage and syncs across tabs.
import { useLocalStorage } from '@omarstahi/react-useful-hooks';
function ThemeToggler() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
);
}useToggle
Simple boolean toggler.
import { useToggle } from '@omarstahi/react-useful-hooks';
function Modal() {
const [isOpen, toggleIsOpen] = useToggle(false);
return (
<>
<button onClick={toggleIsOpen}>Open Modal</button>
{isOpen && <div>Modal Content</div>}
</>
);
}useFetch
Fetches data from a URL.
import { useFetch } from '@omarstahi/react-useful-hooks';
function UserList() {
const { data, loading, error, refetch } = useFetch('https://api.example.com/users');
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<button onClick={refetch}>Refresh</button>
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
</div>
);
}usePagination
Handles pagination logic.
import { usePagination } from '@omarstahi/react-useful-hooks';
function PaginatedList({ items }) {
const {
currentPage,
totalPages,
currentData,
nextPage,
prevPage,
setPage
} = usePagination(items, 10);
return (
<div>
<ul>
{currentData.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
<div>
<button onClick={prevPage} disabled={currentPage === 1}>Prev</button>
<span>{currentPage} / {totalPages}</span>
<button onClick={nextPage} disabled={currentPage === totalPages}>Next</button>
</div>
</div>
);
}Contributing
Contributions are welcome! Please open an issue or submit a pull request.
License
MIT
