BlockDex

Components

Registries

Free blocks

Method

BlockDex

Components

Registries

Free blocks

Method

Open API

BlockDex

Components

Registries

Free blocks

Method

Open API

Components/guarahooks/use-session-storage

UseSessionStorage

guarahooks/use-session-storage
FreeHook

Synchronizes a value with sessionStorage.

Live preview

live · rendered by the registry
Rendered by guarahooks on their own page — this is the component running, not a screenshot of it.

Install it

npx shadcn@latest add https://guarahooks.com/r/use-session-storage.json

Source

registry/hooks/use-session-storage.tsxguarahooks.com/r/use-session-storage.json
1'use client';
2
3import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
5interface UseSessionStorageOptions<T> {
6 serialize?: (value: T) => string;
7 deserialize?: (value: string) => T;
8}
9
10/**
11 * Hook to synchronize a value with sessionStorage in a type-safe, performant, and cross-tab reactive way.
12 *
13 * @param key sessionStorage key
14 * @param initialValue Initial value
15 * @param options Custom serialization/deserialization functions
16 */
17function useSessionStorage<T>(
18 key: string,
19 initialValue: T,
20 options?: UseSessionStorageOptions<T>,
21) {
22 // Memoize serialize/deserialize to avoid unnecessary dependencies
23 const serialize = useMemo(
24 () => options?.serialize ?? JSON.stringify,
25 [options?.serialize],
26 );
27
28 const deserialize = useMemo(
29 () => options?.deserialize ?? JSON.parse,
30 [options?.deserialize],
31 );
32
33 // Ref to keep the initial value stable
34 const initialRef = useRef(initialValue);
35
36 const readValue = useCallback((): T => {
37 if (typeof window === 'undefined') return initialRef.current;
38
39 try {
40 const item = window.sessionStorage.getItem(key);
41
42 return item != null ? (deserialize(item) as T) : initialRef.current;
43 } catch (error) {
44 console.warn(
45 `[useSessionStorage] Error reading key "${key}" from sessionStorage:`,
46 error,
47 );
48
49 return initialRef.current;
50 }
51 }, [key, deserialize]);
52
53 // State synchronized with sessionStorage
54 const [storedValue, setStoredValue] = useState<T>(readValue);
55
56 const setValue = useCallback(
57 (value: T | ((val: T) => T)) => {
58 try {
59 setStoredValue((prev) => {
60 const valueToStore = value instanceof Function ? value(prev) : value;
61
62 window.sessionStorage.setItem(key, serialize(valueToStore));
63
64 return valueToStore;
65 });
66 } catch (error) {
67 console.warn(
68 `[useSessionStorage] Error setting key "${key}" in sessionStorage:`,
69 error,
70 );
71 }
72 },
73 [key, serialize],
74 );
75
76 // Synchronize between tabs
77 useEffect(() => {
78 const handleStorage = (event: StorageEvent) => {
79 if (event.storageArea === window.sessionStorage && event.key === key) {
80 setStoredValue(readValue());
81 }
82 };
83
84 window.addEventListener('storage', handleStorage);
85
86 return () => window.removeEventListener('storage', handleStorage);
87 }, [key, readValue]);
88
89 // Update the value if the key changes
90 useEffect(() => {
91// … truncated

Files it writes

  • registry/hooks/use-session-storage.tsx

Facts

Registry
guarahooks
Type
registry:hook
Access
Free
Files written
1
Licence
MIT
First indexed
2026-08-03
Last confirmed
yesterday

Go to the source

Docs on guarahooks guarahooks.com h3rmel/guarahooks on GitHub Raw registry item This item as JSON

More from guarahooks

All 100 items
Same registry, same kind — the ones you would have found next
ComponentRegistryKindAccessInstallsCommand
UseAbortControlleruse-abort-controllerguarahooksHooksFreeno deps
UseArrayStateuse-array-stateguarahooksHooksFreeno deps
UseAxiosuse-axiosguarahooksHooksFreeno deps
UseBatteryStatususe-battery-statusguarahooksHooksFreeno deps
UseBetterAuthuse-better-authguarahooksHooksFreeno deps
UseClickOutsideuse-click-outsideguarahooksHooksFreeno deps
UseConfirmuse-confirmguarahooksHooksFreeno deps
UseCookieuse-cookieguarahooksHooksFreeno deps
BlockDex

Built by

Kynth Studio

Index

Components
Registries
Method
Open API

Guides

shadcn component libraries
Best shadcn registries
Free shadcn blocks

Reference

Corpus counts
Crawl health
hello@kynth.studio
Privacy
Terms

BlockDex

BlockDex

Built by

Kynth Studio

Index

Components
Registries
Method
Open API

Guides

shadcn component libraries
Best shadcn registries
Free shadcn blocks

Reference

Corpus counts
Crawl health
hello@kynth.studio
Privacy
Terms

BlockDex

BlockDex

Built by

Kynth Studio

Index

Components
Registries
Method
Open API

Guides

shadcn component libraries
Best shadcn registries
Free shadcn blocks

Reference

Corpus counts
Crawl health
hello@kynth.studio
Privacy
Terms

BlockDex