on 59995bf help sign in
bridge/src/lib/useLocalStorageState.js
38 lines 1.1 kB history raw
1import { useState, useEffect } 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 useEffect(() => {
29 try {
30 localStorage.setItem(key, JSON.stringify(state));
31 } catch {
32 // if user is in private mode or has storage restriction
33 // localStorage can throw. Also JSON.stringify can throw.
34 }
35 }, [key, state]);
37 return [state, setState];