2.2.3 • Published 11 months ago
@buzuosheng/use-localstorage v2.2.3
use-localstorage
A lightweight React Hook for elegant localStorage management with support for data expiration and namespace functionality.
✨ Features
- 🚀 Data expiration support
- 🔖 Namespace (prefix) support
- 💪 Full TypeScript support
- 🎯 Automatic serialization and deserialization
- 🔄 Cross-tab synchronization
- 🛡️ Type-safe implementation
📦 Installation
# Using npm
npm install @buzuosheng/use-localstorage
# Using yarn
yarn add @buzuosheng/use-localstorage
# Using pnpm
pnpm add @buzuosheng/use-localstorage🔨 Usage
import { useLocalStorage } from '@buzuosheng/use-localstorage';
// Basic usage
const [value, setValue] = useLocalStorage('key');
// With expiration time and prefix
const [value, setValue] = useLocalStorage('key', {
age: '7d', // Supports: 's'(seconds), 'm'(minutes), 'h'(hours), 'd'(days)
prefix: 'app:', // Custom prefix
initialValue: 'default' // Initial value
});📝 API
useLocalStorage(key, options?)
Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| key | string | Yes | - | localStorage key name |
| options | object | No | - | Configuration options |
Options
| Option | Type | Default | Description |
|---|---|---|---|
| age | string | '7d' | Data expiration time |
| prefix | string | 'Prefix:' | Key prefix |
| initialValue | any | undefined | Initial value |
Return Value
[storedValue, setValue]: [T | undefined, (value: T) => void]🌰 Examples
Basic Usage
import { useLocalStorage } from '@buzuosheng/use-localstorage';
function App() {
const [name, setName] = useLocalStorage('name', {
age: '1d',
initialValue: 'John'
});
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}Storing Objects
interface User {
name: string;
age: number;
}
function App() {
const [user, setUser] = useLocalStorage<User>('user', {
initialValue: { name: 'John', age: 25 }
});
return (
<div>
<input
value={user?.name}
onChange={(e) => setUser({ ...user, name: e.target.value })}
/>
</div>
);
}📄 License
MIT © buzuosheng
2.2.3
11 months ago
3.0.0
2 years ago
2.2.2
4 years ago
2.2.1
5 years ago
2.2.0
5 years ago
1.2.0
5 years ago
1.1.0
5 years ago
2.0.3
5 years ago
2.0.2
5 years ago
2.0.4
5 years ago
2.1.0
5 years ago
2.0.1
5 years ago
1.0.0
5 years ago
0.12.0
5 years ago
0.11.0
5 years ago
0.10.0
5 years ago
0.9.0
5 years ago
0.8.0
5 years ago
0.7.0
5 years ago
0.6.0
5 years ago
0.3.0
5 years ago
0.2.0
5 years ago
0.5.0
5 years ago
0.4.0
5 years ago
0.1.0
5 years ago