use-session-storage

useSessionStorage

A powerful, production-ready React hook for SessionStorage 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:

Ask DeepWiki

🎯 Key Features

📦 Installation

npm i @asudbury/use-session-storage

🚀 Quick Start

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>
  );
}

🔧 Advanced Usage

With TypeScript

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>
  );
}

With Validation

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;
  },
});

With Debouncing

const [text, setText] = useSessionStorage('text', '', {
  debounceMs: 500, // Wait 500ms before writing to storage
});

⚙️ Configuration Options

interface UseSessionStorageOptions<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] = useSessionStorage('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:

📖 API Reference

Return Value

const [value, setValue, actions] = useSessionStorage(key, defaultValue, options);

🔧 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

❤️ Support My Work

Buy Me A Coffee