Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active October 11, 2019 19:21
Show Gist options
  • Save freddi301/650b8ac8ce927fb2ddc957e85efdc895 to your computer and use it in GitHub Desktop.
Save freddi301/650b8ac8ce927fb2ddc957e85efdc895 to your computer and use it in GitHub Desktop.
useLocalStorage #react #hook
import { useState } from "react";
export function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value: T) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} 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