react-sessionstorage-ttl-hook
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

📦 react-sessionstorage-ttl-hook

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.


✨ Features

  • ✅ 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)

📦 Installation

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


Package Sidebar

Install

npm i react-sessionstorage-ttl-hook

Weekly Downloads

27

Version

1.0.7

License

MIT

Unpacked Size

10.4 kB

Total Files

10

Last publish

Collaborators

  • sohamnakhare15