Skip to content

Instantly share code, notes, and snippets.

@LishuGupta652
Forked from joshuacerbito/useLocalStorage.js
Created April 16, 2020 20:26
Show Gist options
  • Save LishuGupta652/ecbafc1764e5127ea09e6e2ae418b7d9 to your computer and use it in GitHub Desktop.
Save LishuGupta652/ecbafc1764e5127ea09e6e2ae418b7d9 to your computer and use it in GitHub Desktop.
Custom React Hook for handling local storage
import { useState } from 'react';
export default function useLocalStorage(key, initialValue) {
const [item, setInnerValue] = useState(() => {
try {
return window.localStorage.getItem(key)
? JSON.parse(window.localStorage.getItem(key))
: initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = value => {
try {
setInnerValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.log(e);
}
};
// Alternatively we could update localStorage inside useEffect ...
// ... but this would run every render and it really only needs ...
// ... to happen when the returned setValue function is called.
/*
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
});
*/
return [item, setValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment