Created
March 23, 2019 07:25
-
-
Save schabluk/a20f70c12a534c59f7cbc8172f29f43d to your computer and use it in GitHub Desktop.
useLocalStorage hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const useLocalStorage = (key, initial) => { | |
let local; | |
try { | |
local = JSON.parse(localStorage.getItem(key)); | |
} catch (err) { | |
// | |
} | |
if (!local) { | |
localStorage.setItem(key, JSON.stringify(initial)); | |
local = initial; | |
} | |
const [state, _setState] = useState(local); | |
const setState = updater => { | |
_setState(old => { | |
let res; | |
if (typeof updater === "function") { | |
res = updater(old); | |
} else { | |
res = updater; | |
} | |
localStorage.setItem(key, JSON.stringify(res)); | |
return res; | |
}); | |
}; | |
return [state, setState]; | |
}; | |
const [infinite, setInfinite] = useLocalStorage("infiniteScrolling", false); |
Author
schabluk
commented
Mar 23, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment