Created
August 12, 2019 17:48
-
-
Save jtulk/6493894dd9e8a7c3ad779c39c94dbe28 to your computer and use it in GitHub Desktop.
React Hook to Create State and Syndicate to 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, useEffect } from "react"; | |
/** | |
* A hook to syndicate and hydrate component state into local storage | |
* @param {string} storageKey - the key to store | |
* @param {*} [defaultVal] - an initial value for syndication | |
*/ | |
function useLocalStorage(storageKey, defaultVal = "") { | |
let initialVal = window.localStorage.getItem(storageKey); | |
if (initialVal) { | |
try { | |
initialVal = JSON.parse(initialVal); | |
} catch (e) { | |
initialVal = defaultVal; | |
// log error here if needed | |
} | |
} else { | |
initialVal = defaultVal; | |
} | |
const [value, setValue] = useState(initialVal); | |
useEffect(() => { | |
const stringifiedVal = JSON.stringify(value); | |
if (stringifiedVal) { | |
window.localStorage.setItem(storageKey, stringifiedVal); | |
} | |
}, [value]); | |
return [value, setValue]; | |
} | |
export default useLocalStorage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment