Created
January 19, 2021 16:35
-
-
Save jogilvyt/4ed46083697abc44d904013b698fffb3 to your computer and use it in GitHub Desktop.
React hook to store state in localStorage
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, useEffect } from "react"; | |
const useStateWithLocalStorage = (defaultValue, key) => { | |
const [value, setValue] = useState(() => { | |
const persistedValue = window.localStorage.getItem(key); | |
return persistedValue !== null ? JSON.parse(persistedValue) : defaultValue; | |
}); | |
useEffect(() => { | |
window.localStorage.setItem(key, JSON.stringify(value)); | |
}, [key, value]); | |
return [value, setValue]; | |
}; | |
export default useStateWithLocalStorage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment