· 5 years ago · Mar 10, 2021, 05:04 PM
1import { useState } from "react";
2
3function useLocalStorage(key, initialValue) {
4 // State to store our value
5 // Pass initial state function to useState so logic is only executed once
6 const [storedValue, setStoredValue] = useState(() => {
7 try {
8 // Get from local storage by key
9 const item = window.localStorage.getItem(key);
10 // Parse stored json or if none return initialValue
11 return item ? JSON.parse(item) : initialValue;
12 } catch (error) {
13 // If error also return initialValue
14 console.log(error);
15 return initialValue;
16 }
17 });
18
19 // Return a wrapped version of useState's setter function that ...
20 // ... persists the new value to localStorage.
21 const setValue = (value) => {
22 try {
23 // Allow value to be a function so we have same API as useState
24 const valueToStore =
25 value instanceof Function ? value(storedValue) : value;
26 // Save state
27 setStoredValue(valueToStore);
28 // Save to local storage
29 window.localStorage.setItem(key, JSON.stringify(valueToStore));
30 } catch (error) {
31 // A more advanced implementation would handle the error case
32 console.log(error);
33 }
34 };
35
36 return [storedValue, setValue];
37}
38
39export default useLocalStorage;