Skip to content

Instantly share code, notes, and snippets.

@Taump
Created January 23, 2020 07:16
Show Gist options
  • Save Taump/0f1a1d5f1617be5fac0195b2bc851631 to your computer and use it in GitHub Desktop.
Save Taump/0f1a1d5f1617be5fac0195b2bc851631 to your computer and use it in GitHub Desktop.
hook local storage
import { useState } from "react";
export const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = value => {
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];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment