diff options
author | eug-vs <eug-vs@keemail.me> | 2020-08-10 00:02:24 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2020-08-10 00:02:24 +0300 |
commit | fd6e663a1bcc43cfc49bda99ccbfab380489324b (patch) | |
tree | ea25ea2c81db0f64e10123dbadd73f361b904da2 /src/hooks/useLocalStorage.ts | |
parent | 359ec6a68ea92b3d1eecf020742157eb3be90b9f (diff) | |
download | which-ui-fd6e663a1bcc43cfc49bda99ccbfab380489324b.tar.gz |
feat!: add useLocalStorage hook
Diffstat (limited to 'src/hooks/useLocalStorage.ts')
-rw-r--r-- | src/hooks/useLocalStorage.ts | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.ts new file mode 100644 index 0000000..faf1411 --- /dev/null +++ b/src/hooks/useLocalStorage.ts @@ -0,0 +1,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]; +}; |