@ndriadev/react-tools
v2.1.2
Published
A React library of hooks, components, utils and types ready to use
Downloads
364
Maintainers
Keywords
Readme
@ndriadev/react-tools
🎯 The Ultimate React Toolkit
115+ Production-Ready Hooks • 9 Smart Components • 25+ Utilities • Full TypeScript
📚 Documentation • 🎮 Live Demos • 🐛 Report Bug • ✨ Request Feature
✨ Why React Tools?
🎨 Developer Experience
- 💎 TypeScript-first with complete type safety
- 🎯 Intuitive APIs that feel natural
- 📖 Rich documentation with live examples
- 🔍 IntelliSense everywhere
⚡ Performance
- 🌳 Tree-shakeable - import only what you need
- 📦 Tiny bundles - optimized for production
- 🚀 Zero dependencies (except React)
- ⚙️ Optimized re-renders
🛠️ Battle-Tested
- ✅ Production-ready hooks and components
- 🧪 Thoroughly tested patterns
- 🔒 Type-safe implementations
- 📱 Cross-platform compatible
🎁 Feature-Rich
- 🎣 115+ hooks across 5 categories
- 🧩 9 components for common patterns
- 🔧 25+ utilities for everyday tasks
- 🌐 Modern Web APIs integrated
🚀 Quick Start
Installation
# npm
npm install @ndriadev/react-tools
# pnpm (recommended)
pnpm add @ndriadev/react-tools
# yarn
yarn add @ndriadev/react-toolsBasic Usage
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>
}Tree-Shakeable Imports
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'📦 What's Inside?
🎣 Hooks (115+)
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>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])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)
})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>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' })🧩 Components (9)
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} />}
/>🔧 Utilities (25+)
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 Support
| Browser | Version | |---------|---------| | Chrome | ≥ 90 | | Firefox | ≥ 88 | | Safari | ≥ 14 | | Edge | ≥ 90 |
React Compatibility: React ≥ 16.8.0 (Hooks support required)
🎯 Use Cases
📱 Modern Web Apps
Perfect for SPAs with complex state management and real-time features
🏢 Enterprise Applications
Battle-tested patterns for large-scale applications with strict requirements
🚀 Rapid Prototyping
Skip boilerplate and focus on features with ready-to-use hooks
📝 Changelog
See CHANGELOG.md for release history and breaking changes.
📄 License
MIT © nDriaDev
📞 Support
- Documentation: futurable.ndria.dev
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: [email protected]
If you find Futurable useful, please consider giving it a ⭐ on GitHub!
