aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useLocalStorage.ts
blob: a604ebeb57181aa1aabada70f4b8a3364e98404b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { useState, useCallback } from 'react';

type Value = string | null;
type Setter = (value: Value) => void;

const useLocalStorage = (key: string): [Value, Setter] => {
  const [state, setState] = useState<Value>(() => localStorage.getItem(key) || null);

  const update: Setter = useCallback(value => {
    if (value) localStorage.setItem(key, value);
    else localStorage.removeItem(key);
    setState(value);
  }, [key]);

  return [state, update];
};


export default useLocalStorage;