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

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

export default (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];
};