Skip to content

Instantly share code, notes, and snippets.

@akirco
Created June 1, 2023 09:59
Show Gist options
  • Save akirco/fe61012dcf5a2c64723e39334f92c606 to your computer and use it in GitHub Desktop.
Save akirco/fe61012dcf5a2c64723e39334f92c606 to your computer and use it in GitHub Desktop.
react hooks-useSafeLocalStorage
import { useState, useEffect } from "react";
export function useSafeLocalStorage(key: string, initialValue: any) {
const [valueProxy, setValueProxy] = useState(() => {
try {
const value = window.localStorage.getItem(key);
return value ? JSON.parse(value) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(valueProxy));
} catch {}
}, [key, valueProxy]);
const setValue = (value: any) => {
setValueProxy(value);
};
return [valueProxy, setValue];
}
@cocshank
Copy link

你好

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