use-session-storage (use-session-storage)
Manages session storage with declarative methods.
v0.1.0
Usage
import { use-session-storage } from "@/hooks"
1"use client";
2
3import React, { useState } from "react";
4
5import { Label } from "@radix-ui/react-label";
6
7import { Button } from "@/components/ui/button";
8import {
9 Card,
10 CardContent,
11 CardDescription,
12 CardHeader,
13 CardTitle,
14} from "@/components/ui/card";
15import { Input } from "@/components/ui/input";
16
17import useSessionStorage from "@/components/hooks/use-session-storage";
18
19// Custom serializer/deserializer for an object
20const userSerializer = (user: { name: string; age: number }) =>
21 JSON.stringify(user);
22const userDeserializer = (str: string) => {
23 try {
24 return JSON.parse(str) as { name: string; age: number };
25 } catch {
26 return { name: "", age: 0 };
27 }
28};
29
30export function UseSessionStorageDemo() {
31 // Object example with custom serializer/deserializer
32 const [user, setUser] = useSessionStorage<{ name: string; age: number }>(
33 "demo-user",
34 { name: "", age: 0 },
35 { serialize: userSerializer, deserialize: userDeserializer }
36 );
37
38 const [ageInput, setAgeInput] = useState("");
39
40 return (
41 <Card className="relative max-w-sm w-full">
42 <CardHeader>
43 <CardTitle>useSessionStorage</CardTitle>
44 <CardDescription>
45 This component uses the <code>useSessionStorage</code> hook to manage
46 a session storage item.
47 </CardDescription>
48 </CardHeader>
49 <CardContent className="space-y-4">
50 <div className="flex flex-col gap-2">
51 <Label>User (object):</Label>
52 <Input
53 type="text"
54 value={user.name}
55 onChange={(e) => setUser({ ...user, name: e.target.value })}
56 placeholder="User name..."
57 />
58 <Input
59 type="number"
60 value={ageInput}
61 onChange={(e) => setAgeInput(e.target.value)}
62 placeholder="User age..."
63 />
64 </div>
65 <div className="flex gap-2">
66 <Button
67 onClick={() => {
68 const age = parseInt(ageInput, 10);
69 if (!isNaN(age)) setUser({ ...user, age });
70 }}
71 size="sm"
72 >
73 Set Age
74 </Button>
75 <Button onClick={() => setUser({ name: "", age: 0 })} size="sm">
76 Clear User
77 </Button>
78 </div>
79 <pre className="text-sm text-muted-foreground bg-accent w-fit px-1 py-0.5 rounded-xs">
80 {JSON.stringify(user)}
81 </pre>
82 </CardContent>
83 </Card>
84 );
85}
86
Install
npx wkkkis-hooks add use-session-storage
Options
Name | Type | Default | Description |
---|---|---|---|
key | string | - | The key to store the value in session storage |
initialValue | string | - | The initial value to store in session storage |
options? | UseSessionStorageOptions | - | The options for the hook |
Cross-Tab Synchronization
- The hook listens for storage events and updates the state if the value changes in another tab or window (for the same session).
Serialization & Deserialization
- By default, values are serialized with JSON.stringify and deserialized with JSON.parse .
- You can provide custom serialize and deserialize functions for non-JSON data or advanced use cases.
Error Handling
- If reading or writing to sessionStorage fails (e.g., quota exceeded, invalid JSON), the hook logs a warning and falls back to the initial value.
SSR & Initial Value
- On the server, the hook always returns the initial value.
- The initial value is only used if there is no value in sessionStorage for the given key.
Best Practices & Caveats
- The hook is client-side only; on the server, it does not interact with sessionStorage.
- Avoid storing sensitive data in sessionStorage.
- Changing the key will re-read and update the value from sessionStorage.
- For best performance, avoid creating new serialize / deserialize functions on every render (use useCallback or useMemo if needed).
Files in this hook
Source | Destination |
---|---|
files/use-session-storage.ts | src/hooks/use-session-storage.ts |