Skip to content

Instantly share code, notes, and snippets.

@aspnetde
Created September 28, 2020 10:03
Show Gist options
  • Save aspnetde/44412d47be8d705e9d317ddea36c5b2f to your computer and use it in GitHub Desktop.
Save aspnetde/44412d47be8d705e9d317ddea36c5b2f to your computer and use it in GitHub Desktop.
A Local Storage React Hook
export function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? (JSON.parse(item) as T) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = (value: T) => {
try {
if (value !== undefined) {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} else {
setStoredValue(initialValue);
window.localStorage.removeItem(key);
}
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment