aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useLocalStorage.ts
blob: 5893317b484d1a4770fdb703f694c768664a282e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { useState, useCallback } from 'react';

function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.log(error);
      return initialValue;
    }
  });

  const setValue = useCallback((value: T) => {
    setStoredValue((originalValue: T) => {
      try {
        const valueToStore = value instanceof Function ? value(originalValue) : value;
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
        return valueToStore;
      } catch (error) {
        console.log(error);
      }
    });
  }, [key]);

  return [storedValue, setValue];
}

export default useLocalStorage;