gatsby-plugin-theme-switcher
Version:
React theme switcher with hooks and preventing the initial flash
31 lines (25 loc) • 874 B
JavaScript
;
exports.__esModule = true;
exports.default = useLocalStorage;
var _react = require("react");
/* eslint-disable no-unused-expressions */
/* eslint-disable no-undef */
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = (0, _react.useState)(() => {
try {
const item = typeof window !== "undefined" ? window.localStorage.getItem(key) : undefined;
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = value => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
typeof window !== "undefined" && window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {// console.log(error);
}
};
return [storedValue, setValue];
}