115+ Production-Ready Hooks โข 9 Smart Components โข 25+ Utilities โข Full TypeScript
๐ Documentation โข ๐ฎ Live Demos โข ๐ Report Bug โข โจ Request Feature
|
|
|
|
# npm
npm install @ndriadev/react-tools
# pnpm (recommended)
pnpm add @ndriadev/react-tools
# yarn
yarn add @ndriadev/react-tools
import { useLocalStorageState, useDebounce, useWebSocket } from '@ndriadev/react-tools'
function App() {
// Persistent state with localStorage sync
const [theme, setTheme] = useLocalStorageState('theme', 'dark')
// Debounced search with automatic cleanup
const [search, setSearch] = useState('')
const debouncedSearch = useDebounce(search, 500)
// WebSocket with auto-reconnect and type-safety
const ws = useWebSocket<MessageType>({
url: 'wss://api.example.com',
reconnect: { attempts: 5, exponentialBackoff: true },
onMessage: (data) => console.log('Received:', data)
})
return <div>Your app here</div>
}
Import only what you need for optimal bundle size:
// โ
Import entire library (tree-shakeable)
import { useState History, useWebSocket } from '@ndriadev/react-tools'
// โ
Import by category
import { useStateHistory } from '@ndriadev/react-tools/hooks/state'
import { useWebSocket } from '@ndriadev/react-tools/hooks/api-dom'
// โ
Import components separately
import { SwitchCase, ErrorBoundary } from '@ndriadev/react-tools/components'
// โ
Import utilities
import { isDeepEqual, mergeObjects } from '@ndriadev/react-tools/utils'
๐๏ธ State Management (17 hooks)
Advanced state management with history, validation, and persistence:
| Hook | Description |
|---|---|
useStateHistory |
useState with undo/redo and time-travel |
useReducerHistory |
useReducer with history tracking |
useLocalStorageState |
Sync state with localStorage |
useSessionStorageState |
Sync state with sessionStorage |
useProxyState |
Deep reactive state with Proxy |
useStateValidator |
State with built-in validation |
useDerivedState |
Computed state from props |
usePrevious |
Track previous value |
useArray |
Array manipulation utilities |
useMap |
Map state management |
useSet |
Set state management |
createPubSubStore |
Global pub/sub state |
// Example: Undo/Redo functionality
const [count, setCount, { undo, redo, canUndo, canRedo }] = useStateHistory(0, 10)
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<button onClick={undo} disabled={!canUndo}>Undo</button>
<button onClick={redo} disabled={!canRedo}>Redo</button>
โป๏ธ Lifecycle (12 hooks)
Enhanced lifecycle hooks with custom comparison and abort control:
useEffectOnce- Run effect only onceuseEffectCompare- Custom dependency comparisonuseEffectDeepCompare- Deep equality checkuseEffectAbortable- Built-in AbortControlleruseLayoutEffect*variantsuseIsMounted- Check mount statususeLogger- Debug lifecycle changes
// Example: Deep comparison for objects
useEffectDeepCompare(() => {
fetchData(filters) // Only runs when filters deeply change
}, [filters])
โก Performance (8 hooks)
Optimize your components with smart memoization:
useMemoizedFn- Stable function referencesuseMemoCompare/useCallbackCompare- Custom comparisonuseLazyRef- Lazy initializationuseMergedRef- Merge multiple refsuseId- Unique IDs (React 18 polyfill)
// Example: Stable callback without dependencies
const handleClick = useMemoizedFn((id) => {
// Always has access to latest state
// But reference never changes
console.log('Clicked:', id, latestState)
})
๐ Events (25 hooks)
Handle user interactions and DOM events efficiently:
Mouse & Touch:
useClickOutside- Detect clicks outside elementuseHover- Hover stateuseDoubleClick- Distinguish single/double clickuseLongPress- Long press detectionuseSwipe- Swipe gesturesusePinchZoom- Pinch-to-zoom
Observers:
useIntersectionObserver- Visibility detectionuseResizeObserver- Element size changesuseMutationObserver- DOM mutations
Keyboard & Actions:
useHotKeys- Keyboard shortcutsusePerformAction- Action delegation patternuseEventListener- Generic event handling
Network & System:
useIsOnline- Online/offline statususeNetwork- Network informationuseBeforeUnload- Prevent page close
// Example: Click outside to close
const ref = useClickOutside(() => setIsOpen(false))
<div ref={ref}>{isOpen && <Dropdown />}</div>
๐ Web APIs (50+ hooks)
Modern browser APIs made easy:
Media:
useAudio/useVideo- Media element controluseMediaDevices- Camera/microphone accessuseDisplayMedia- Screen sharingusePIP- Picture-in-PictureuseSpeechRecognition/useSpeechSynthesis
Communication:
useWebSocket- WebSocket with reconnectionuseWebWorker- Multi-threadinguseFetch- Fetch with abort & cachinguseEventSource- Server-Sent EventsuseBroadcastChannel- Cross-tab messaging
Device & Sensors:
useBattery- Battery statususeGeolocation- GPS locationuseDeviceOrientation/useDeviceMotionuseVibrate- Haptic feedback
UI & UX:
useFullscreen- Fullscreen modeuseClipboard- Clipboard operationsuseColorScheme- Dark/light modeuseShare- Web Share APIuseEyeDropper- Color picker
// Example: WebSocket with auto-reconnect
const ws = useWebSocket({
url: 'wss://api.example.com',
reconnect: {
attempts: 5,
exponentialBackoff: true
},
parser: 'json',
onMessage: (data) => updateUI(data)
})
ws.sendJSON({ type: 'ping' })
Conditional Rendering:
// Show/Hide with fallback
<Show when={isLoggedIn} fallback={<Login />}>
<Dashboard />
</Show>
// Switch-case logic
<SwitchCase.Switch>
<SwitchCase.Case when={status === 'loading'}>
<Spinner />
</SwitchCase.Case>
<SwitchCase.Case when={status === 'error'}>
<Error />
</SwitchCase.Case>
</SwitchCase.Switch>
List Rendering:
// Optimized list rendering
<For each={items} fallback={<EmptyState />}>
{(item, index) => <ItemCard key={item.id} {...item} />}
</For>
Error Handling:
// Error boundary with reset
<ErrorBoundary
fallback={(error, reset) => (
<ErrorDisplay error={error} onReset={reset} />
)}
onError={(error) => logToService(error)}
>
<App />
</ErrorBoundary>
Lazy Loading:
// Advanced lazy loading with retry
<LazyComponent
loader={() => import('./HeavyComponent')}
loading={<Skeleton />}
error={(retry) => <ErrorWithRetry onRetry={retry} />}
/>
Type Guards:
isDeepEqual/isShallowEqual- Equality checksisMouseEvent/isTouchEvent- Event type guardsisAsync- Async function detectionisClient- SSR detection
Object & Array:
mergeObjects- Deep mergegetObjectFromDottedString- Path access ("user.profile.name")uniqueElementsArray- Remove duplicatesalphanumericCompare- Natural sorting
String:
changeStringCase- Convert between casesdetectBrowser- Browser detection
DOM:
clickElementOnKeydownEvent- Accessibility helperhotKeyHandler- Keyboard shortcutsgetBase64- File conversion
Patterns:
PublishSubscribePattern- Pub/Sub implementationEventsPattern- Event emitterlazy- Lazy function execution
| Browser | Version |
|---|---|
| Chrome | โฅ 90 |
| Firefox | โฅ 88 |
| Safari | โฅ 14 |
| Edge | โฅ 90 |
React Compatibility: React โฅ 16.8.0 (Hooks support required)
|
Perfect for SPAs with complex state management and real-time features |
Battle-tested patterns for large-scale applications with strict requirements |
Skip boilerplate and focus on features with ready-to-use hooks |
See CHANGELOG.md for release history and breaking changes.
MIT ยฉ nDriaDev
- Documentation: futurable.ndria.dev
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: info@ndria.dev
If you find Futurable useful, please consider giving it a โญ on GitHub!