@asudbury/use-local-storage
v1.0.1
Published
A powerful React hook for LocalStorage management with TypeScript support, serialization, and comprehensive event handling
Maintainers
Readme
useLocalStorage
A powerful, production-ready React hook for LocalStorage management with comprehensive serialization support, type safety, and event handling.
📚 DeepWiki Project Knowledge Base
Explore the full documentation, architecture, and deep technical notes for this project on DeepWiki:
- Comprehensive guides, diagrams, and design decisions
- Contributor onboarding and advanced usage tips
- Maintainer notes, troubleshooting, and best practices
This is the canonical knowledge base for the project. If you're contributing, maintaining, or deploying, start here!
🎯 Key Features
- 🔄 Automatic Serialization: JSON serialization/deserialization with error handling
- 🛡️ Type Safe: Full TypeScript support with generic types
- ⚡ Performance Optimized: Efficient state management and memory leak prevention
- 🎛️ Event Handling: Listen to storage changes across tabs/windows
- 📦 Default Values: Support for default values and fallbacks
- 🔍 Validation: Optional value validation with custom validators
- 🚫 SSR Safe: Server-side rendering compatible
- 🔄 Synchronization: Automatic sync across multiple hook instances
- ⏱️ Debounced Updates: Optional debounced writes for performance
- 📊 State Management: Comprehensive loading and error states
📦 Installation
npm i @asudbury/use-local-storage🚀 Quick Start
import useLocalStorage from '@asudbury/use-local-storage';
function MyComponent() {
const [value, setValue, { loading, error, remove }] = useLocalStorage('my-key', 'default-value');
return (
<div>
<input value={value} onChange={(e) => setValue(e.target.value)} disabled={loading} />
<button onClick={remove}>Clear</button>
{error && <p>Error: {error.message}</p>}
</div>
);
}🔧 Advanced Usage
With TypeScript
interface User {
id: number;
name: string;
email: string;
}
function UserProfile() {
const [user, setUser] = useLocalStorage<User>('user', {
id: 0,
name: '',
email: '',
});
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}With Validation
const [count, setCount] = useLocalStorage('count', 0, {
validator: (value) => {
if (typeof value !== 'number') throw new Error('Must be a number');
if (value < 0) throw new Error('Must be positive');
return value;
},
});With Debouncing
const [text, setText] = useLocalStorage('text', '', {
debounceMs: 500, // Wait 500ms before writing to storage
});⚙️ Configuration Options
interface UseLocalStorageOptions<T> {
serializer?: {
parse: (value: string) => T;
stringify: (value: T) => string;
};
validator?: (value: any) => T;
debounceMs?: number;
syncAcrossInstances?: boolean;
onError?: (error: Error) => void;
}🔄 Event Handling
Listen to storage changes across tabs and windows:
const [theme, setTheme] = useLocalStorage('theme', 'light');
// Automatically syncs when changed in other tabs
useEffect(() => {
console.log('Theme changed to:', theme);
}, [theme]);🛡️ Error Handling
The hook provides comprehensive error handling for:
- JSON parsing errors
- Storage quota exceeded
- Invalid values
- Validation failures
📖 API Reference
Return Value
const [value, setValue, actions] = useLocalStorage(key, defaultValue, options);value: Current value from localStoragesetValue: Function to update the valueactions: Object with additional actions and statesloading: Boolean indicating if operation is in progresserror: Error object if operation failedremove: Function to remove the item from storagereset: Function to reset to default value
🔧 TypeScript Support
Full TypeScript support with proper type inference and IntelliSense for complete type safety.
📄 License
MIT © Adrian Sudbury
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📞 Support
If you have any questions or need help, please Open an issue or use the links above.
Made with ❤️ for the React community
