
A powerful, production-ready React hook for SessionStorage management with comprehensive serialization support, type safety, and event handling.
Explore the full documentation, architecture, and deep technical notes for this project on DeepWiki:
npm i @asudbury/use-session-storage
import useSessionStorage from '@asudbury/use-session-storage';
function MyComponent() {
const [value, setValue, { loading, error, remove }] = useSessionStorage(
'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>
);
}
interface User {
id: number;
name: string;
email: string;
}
function UserProfile() {
const [user, setUser] = useSessionStorage<User>('user', {
id: 0,
name: '',
email: '',
});
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
const [count, setCount] = useSessionStorage('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;
},
});
const [text, setText] = useSessionStorage('text', '', {
debounceMs: 500, // Wait 500ms before writing to storage
});
interface UseSessionStorageOptions<T> {
serializer?: {
parse: (value: string) => T;
stringify: (value: T) => string;
};
validator?: (value: any) => T;
debounceMs?: number;
syncAcrossInstances?: boolean;
onError?: (error: Error) => void;
}
Listen to storage changes across tabs and windows:
const [theme, setTheme] = useSessionStorage('theme', 'light');
// Automatically syncs when changed in other tabs
useEffect(() => {
console.log('Theme changed to:', theme);
}, [theme]);
The hook provides comprehensive error handling for:
const [value, setValue, actions] = useSessionStorage(key, defaultValue, options);
value: Current value from sessionStoragesetValue: Function to update the valueactions: Object with additional actions and states
loading: Boolean indicating if operation is in progresserror: Error object if operation failedremove: Function to remove the item from storagereset: Function to reset to default valueFull TypeScript support with proper type inference and IntelliSense for complete type safety.
MIT © Adrian Sudbury
Contributions are welcome! Please feel free to submit a Pull Request.
If you have any questions or need help, please Open an issue or use the links above.
Made with ❤️ for the React community