on master help sign in
bridge/src/lib/useLocalStorageState.js
43 lines 1.2 kB history raw
1import { useCallback, useState } from 'react';
3/**
4 * useLocalStorageState is useState but it persists to localStorage
5 *
6 * inspired by:
7 * https://github.com/streamich/react-use/blob/master/src/useLocalStorage.ts
8 * https://usehooks.com/useLocalStorage/
9 */
10export default function useLocalStorageState(key, initialValue) {
11 const [state, _setState] = useState(() => {
12 try {
13 const value = localStorage.getItem(key);
14 if (value === null) {
15 localStorage.setItem(key, JSON.stringify(initialValue));
16 return initialValue;
17 } else {
18 return JSON.parse(value);
19 }
20 } catch {
21 // if user is in private mode or has storage restriction
22 // localStorage can throw. JSON.parse and JSON.stringify
23 // can throw, too.
24 return initialValue;
25 }
26 });
28 const setState = useCallback(
29 value => {
30 try {
31 localStorage.setItem(key, JSON.stringify(value));
32 } catch {
33 // if user is in private mode or has storage restriction
34 // localStorage can throw. Also JSON.stringify can throw.
35 }
37 _setState(value);
38 },
39 [key]
40 );
42 return [state, setState];