diff options
Diffstat (limited to 'src/hooks/useLocalStorage.ts')
-rw-r--r-- | src/hooks/useLocalStorage.ts | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.ts new file mode 100644 index 0000000..a604ebe --- /dev/null +++ b/src/hooks/useLocalStorage.ts @@ -0,0 +1,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; + |