diff options
Diffstat (limited to 'src/hooks/useLocalStorage.js')
-rw-r--r-- | src/hooks/useLocalStorage.js | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/src/hooks/useLocalStorage.js b/src/hooks/useLocalStorage.js new file mode 100644 index 0000000..6dbed36 --- /dev/null +++ b/src/hooks/useLocalStorage.js @@ -0,0 +1,17 @@ +import { useState } from "react"; + +const useLocalStorage = (key, initialValue) => { + const storedVal = localStorage[key] + ? JSON.parse(localStorage[key]) || initialValue + : initialValue; + const [value, setValue] = useState(storedVal); + + function update(newValue) { + localStorage[key] = JSON.stringify(newValue); + setValue(newValue); + } + + return [value, update]; +}; + +export default useLocalStorage; |