Skip to content

Instantly share code, notes, and snippets.

@schabluk
Created March 23, 2019 07:25
Show Gist options
  • Save schabluk/a20f70c12a534c59f7cbc8172f29f43d to your computer and use it in GitHub Desktop.
Save schabluk/a20f70c12a534c59f7cbc8172f29f43d to your computer and use it in GitHub Desktop.
useLocalStorage hook
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);
@schabluk
Copy link
Author

<Button onClick={() => setInfinite(old => !old)}>
  Toggle {infinite ? "Pagination" : "Infinite Scrolling"}
</Button>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment