-
Notifications
You must be signed in to change notification settings - Fork 937
Expand file tree
/
Copy pathuse-cached-state.ts
More file actions
36 lines (34 loc) · 888 Bytes
/
use-cached-state.ts
File metadata and controls
36 lines (34 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { useSyncExternalStore } from 'react';
export const useCachedState = <T>(key: string) => {
let value: T | undefined;
if (
'localStorage' in global &&
typeof global.localStorage.getItem === 'function'
) {
const storedValue = global.localStorage.getItem(key);
if (storedValue !== null && storedValue !== 'undefined') {
try {
value = JSON.parse(storedValue) as T;
} catch (_exception) {
console.warn(
'Failed to load stored value for',
key,
'with value',
storedValue,
);
}
}
}
return [
useSyncExternalStore(
() => () => {},
() => value,
() => undefined,
),
function setValue(newValue: T | undefined) {
if ('localStorage' in global) {
global.localStorage.setItem(key, JSON.stringify(newValue));
}
},
] as const;
};