function useLocalStorageState(
key,
defaulValue,
{ desirialize = JSON.parse, serialize = JSON.stringify } = {}
) {
const [state, setState] = useState(() => {
var keyInLocalStorage = window.localStorage.getItem(key);
if (keyInLocalStorage) {
try {
return desirialize(keyInLocalStorage);
} catch (error) {
window.localStorage.removeItem(key);
}
}
return typeof defaulValue == "function" ? defaulValue() : defaulValue;
});
const prevKeyRef = useRef(key);
useEffect(() => {
const prevKey = prevKeyRef.current;
if (prevKey !== key) {
window.localStorage.removeItem(prevKey);
}
prevKeyRef.current = key;
window.localStorage.setItem(key, serialize(state));
}, [key, state, serialize]);
return [state, setState];
}