react use localstorage hook

Solutions on MaxInterview for react use localstorage hook by the best coders in the world

showing results for - "react use localstorage hook"
Theo
23 Apr 2018
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