A lightweight React hook to store state in sessionStorage
with TTL (Time To Live), auto-expiry, and SSR-safe behavior. Useful for caching temporary data that should disappear after a set time — like form drafts, search filters, or transient UI state.
- ✅ Simple React-style
[value, setValue]
API - 🕒 Automatically expires after specified TTL (in milliseconds)
- 🧹 Automatically removes expired keys from
sessionStorage
- 🔒 Fully SSR-safe — avoids crashes in Next.js or server-rendered apps
- 🔧 TypeScript ready
- ⚛️ Works with React
16.8+
(first version with hooks)
npm install react-sessionstorage-ttl-hook
```tsx
import React from 'react';
import useSessionStorageWithTTL from 'react-sessionstorage-ttl-hook';
function CounterWithTTL() {
const [count, setCount] = useSessionStorageWithTTL<number>(
'counter',
0,
30000 // 30 seconds
);
return (
<div>
<h2>Counter with TTL</h2>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
type UserProfile = { name: string; age: number };
const [profile, setProfile] = useSessionStorageWithTTL<UserProfile>(
'user-profile',
{ name: '', age: 0 },
900000 // 15 minutes
);
setProfile({ name: 'XYZ', age: 30 });