MCPcopy Create free account
hub / github.com/coryhouse/react-state-demo / useLocalStorage

Function useLocalStorage

src/useLocalStorage.js:3–29  ·  view source on GitHub ↗
(key, initialValue)

Source from the content-addressed store, hash-verified

1import { useState } from "react";
2
3export default function useLocalStorage(key, initialValue) {
4 // Pass initial state function to useState so logic is only executed once
5 const [storedValue, setStoredValue] = useState(() => {
6 try {
7 const item = window.localStorage.getItem(key);
8 return item ? JSON.parse(item) : initialValue;
9 } catch (error) {
10 console.log(error);
11 return initialValue;
12 }
13 });
14
15 // Return a wrapped version of useState's setter function that
16 // persists the new value to localStorage.
17 const setValue = (value) => {
18 try {
19 // Allow value to be a function so we have same API as useState
20 const valToStore = value instanceof Function ? value(storedValue) : value;
21 setStoredValue(valToStore);
22 window.localStorage.setItem(key, JSON.stringify(valToStore));
23 } catch (error) {
24 console.log(error);
25 }
26 };
27
28 return [storedValue, setValue];
29}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected