MCPcopy Create free account
hub / github.com/MaterializeInc/materialize / useLocalStorage

Function useLocalStorage

console/src/hooks/useLocalStorage.ts:14–38  ·  view source on GitHub ↗
(
  key: string,
  defaultValue: T,
)

Source from the content-addressed store, hash-verified

12import storageAvailable from "~/utils/storageAvailable";
13
14function useLocalStorage<T>(
15 key: string,
16 defaultValue: T,
17): [T, Dispatch<SetStateAction<T>>] {
18 const [value, setValue] = useState(() => {
19 let currentValue = defaultValue;
20
21 if (storageAvailable("localStorage")) {
22 const localStorageValue = localStorage.getItem(key);
23 if (localStorageValue !== null) {
24 currentValue = JSON.parse(localStorageValue) as T;
25 }
26 }
27
28 return currentValue;
29 });
30
31 useEffect(() => {
32 if (storageAvailable("localStorage")) {
33 localStorage.setItem(key, JSON.stringify(value));
34 }
35 }, [value, key]);
36
37 return [value, setValue];
38}
39
40export default useLocalStorage;

Callers 4

MfaAlertContentFunction · 0.85
IndexListFunction · 0.85
useShowSystemObjectsFunction · 0.85

Calls 2

storageAvailableFunction · 0.85
parseMethod · 0.45

Tested by

no test coverage detected