@fremtind/jkl-react-hooks
Version:
Jøkul react button components
28 lines (27 loc) • 859 B
JavaScript
import { useCallback, useState } from "react";
const useLocalStorage = (key, defaultValue) => {
const [state, setState] = useState(() => {
if (typeof window === "undefined" || !localStorage) {
return defaultValue;
}
const storedValue = JSON.parse(localStorage.getItem(key) || "null");
return storedValue || defaultValue;
});
const updateState = useCallback(
(setStateAction) => {
setState((previousValue) => {
const newValue = typeof setStateAction === "function" ? setStateAction(previousValue) : setStateAction;
if (typeof window !== "undefined" && localStorage) {
localStorage.setItem(key, JSON.stringify(newValue));
}
return newValue;
});
},
[key]
);
return [state, updateState];
};
export {
useLocalStorage
};
//# sourceMappingURL=useLocalStorage.js.map