1import { useState } from "react";
2
3export const useLocalStorage = (key, initialValue) => {
4 const [storedValue, setStoredValue] = useState(() => {
5 try {
6 const item = window.localStorage.getItem(key);
7 return item ? JSON.parse(item) : initialValue;
8 } catch (err) {
9 console.error(err);
10 return initialValue;
11 }
12 });
13
14 const setValue = value => {
15 try {
16 const valueToStore =
17 value instanceof Function ? value(storedValue) : value;
18 setStoredValue(valueToStore);
19 window.localStorage.setItem(key, JSON.stringify(valueToStore));
20 } catch (err) {
21 console.error(err);
22 }
23 };
24
25 return [storedValue, setValue];
26};
27
28export default useLocalStorage;
29