Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Storage Custom Hooks in JavaScript

Write reusable storage hooks in JavaScript like useLocalStorage, with defaults, expiry and cross-tab sync. Includes a fixed setter bug, explanation and output.

AdvancedJavaScript LocalStorage and SessionStorageExample 9 of 10

Run this in the browser console or a page script. localStorage and sessionStorage are browser features, so plain Node will not have them.

storage-custom-hooks.js
1// Method 1: useLocalStorage hook (React-like)
2function useLocalStorage(key, initialValue) {
3 let storedValue = (function() {
4 try {
5 const item = window.localStorage.getItem(key);
6 return item ? JSON.parse(item) : initialValue;
7 } catch (error) {
8 return initialValue;
9 }
10 })();
11
12 const setValue = function(value) {
13 try {
14 storedValue = value;
15 window.localStorage.setItem(key, JSON.stringify(value));
16 } catch (error) {
17 console.error('Error setting localStorage:', error);
18 }
19 };
20
21 return [storedValue, setValue];
22}
23
24// Usage
25const [name, setName] = useLocalStorage('name', '');
26setName('John');
27
28// The value is a snapshot, so read again to see the saved name
29const [savedName] = useLocalStorage('name', '');
30console.log('Name:', savedName);
31
32// Method 2: useSessionStorage hook
33function useSessionStorage(key, initialValue) {
34 let storedValue = (function() {
35 try {
36 const item = window.sessionStorage.getItem(key);
37 return item ? JSON.parse(item) : initialValue;
38 } catch (error) {
39 return initialValue;
40 }
41 })();
42
43 const setValue = function(value) {
44 try {
45 storedValue = value;
46 window.sessionStorage.setItem(key, JSON.stringify(value));
47 } catch (error) {
48 console.error('Error setting sessionStorage:', error);
49 }
50 };
51
52 return [storedValue, setValue];
53}
54
55// Method 3: useStorage with options
56function useStorage(key, initialValue, options = {}) {
57 const storage = options.storage || localStorage;
58 const serializer = options.serializer || JSON;
59
60 let storedValue = (function() {
61 try {
62 const item = storage.getItem(key);
63 return item ? serializer.parse(item) : initialValue;
64 } catch (error) {
65 return initialValue;
66 }
67 })();
68
69 const setValue = function(value) {
70 try {
71 storedValue = value;
72 storage.setItem(key, serializer.stringify(value));
73 } catch (error) {
74 console.error('Storage error:', error);
75 }
76 };
77
78 const removeValue = function() {
79 try {
80 storage.removeItem(key);
81 storedValue = initialValue;
82 } catch (error) {
83 console.error('Remove error:', error);
84 }
85 };
86
87 return [storedValue, setValue, removeValue];
88}
89
90// Method 4: Storage hook with expiration
91function useStorageWithExpiry(key, initialValue, ttl) {
92 let storedValue = (function() {
93 try {
94 const item = localStorage.getItem(key);
95 if (!item) return initialValue;
96
97 const parsed = JSON.parse(item);
98 if (Date.now() > parsed.expiry) {
99 localStorage.removeItem(key);
100 return initialValue;
101 }
102
103 return parsed.value;
104 } catch (error) {
105 return initialValue;
106 }
107 })();
108
109 const setValue = function(value) {
110 try {
111 const item = {
112 value: value,
113 expiry: Date.now() + ttl
114 };
115 storedValue = value;
116 localStorage.setItem(key, JSON.stringify(item));
117 } catch (error) {
118 console.error('Storage error:', error);
119 }
120 };
121
122 return [storedValue, setValue];
123}
124
125// Method 5: Storage hook with sync
126function useSyncedStorage(key, initialValue) {
127 let storedValue = (function() {
128 try {
129 const item = localStorage.getItem(key);
130 return item ? JSON.parse(item) : initialValue;
131 } catch (error) {
132 return initialValue;
133 }
134 })();
135
136 // Listen for changes from other tabs
137 window.addEventListener('storage', function(e) {
138 if (e.key === key) {
139 storedValue = JSON.parse(e.newValue);
140 }
141 });
142
143 const setValue = function(value) {
144 try {
145 storedValue = value;
146 localStorage.setItem(key, JSON.stringify(value));
147 } catch (error) {
148 console.error('Storage error:', error);
149 }
150 };
151
152 return [storedValue, setValue];
153}

Sample Output

Name: John

Printed from a second hook call, which reads the value saved by setName.

In this one

  • What the hook pattern returns
  • How to read storage with a default
  • Why destructuring a single value broke the original
  • How to add expiry and cross-tab sync to a hook

How it works

  1. 1

    useLocalStorage reads "name" and falls back to an empty string.

  2. 2

    setName("John") saves it as JSON.

  3. 3

    Calling the hook again reads "John".

  4. 4

    useStorage adds options and removeValue.

  5. 5

    useStorageWithExpiry and useSyncedStorage add expiry and sync.

Edge cases

Stale value

The first name variable still holds the old value after setName.

The value is a snapshot. Read again, or use a real state library.

Corrupt JSON

A broken stored value would throw on parse.

The try/catch falls back to initialValue.

Listener build-up

Each useSyncedStorage call adds another storage listener.

Remove listeners when they are no longer needed.

What's going on

A hook is a small function that packs some logic and returns a value plus a way to change it. React made the pattern popular with useState. This file copies that style for browser storage without React.

useLocalStorage(key, initialValue) reads the key once. If it exists, it parses the JSON. If not, or if parsing fails, it uses initialValue. It returns an array of two things: the stored value and a setValue function that saves new values as JSON.

The hook keeps the value in a let variable. setValue updates it and saves it. Like React, the returned value is a snapshot, so the usage calls the hook again to read the saved name.

useSessionStorage is the same hook for sessionStorage.

useStorage is the generic version. It takes options: which storage to use and which serializer, an object with parse and stringify. It also returns a third function, removeValue, which deletes the key and resets the value to initialValue.

useStorageWithExpiry saves { value, expiry } and treats old data as missing. useSyncedStorage listens for the storage event, so when another tab changes the key, this tab's value updates too.

Benefits: reusable code, a consistent API, built-in error handling, and with TypeScript, type safety. Use cases are React components, state management, preferences and form data. Best practices: handle errors, provide defaults, support options and document usage.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does useLocalStorage return?

Pick an answer to check it.

Question 2

What does removeValue in useStorage do?

Pick an answer to check it.

Questions people ask

Is this a real React hook?

No. It copies the shape. In React you would combine useState and useEffect.

What was the bug?

It destructured one value as if it were a pair, so the setter was undefined and nothing saved.

What is a serializer?

An object with parse and stringify, like JSON, that turns values into text and back.