Last active
April 16, 2020 20:26
-
-
Save joshuacerbito/409bfd0f6a8aef4599340e64a25e9334 to your computer and use it in GitHub Desktop.
Custom React Hook for handling local storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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