Skip to content

Instantly share code, notes, and snippets.

@jtulk
Created August 12, 2019 17:48
Show Gist options
  • Save jtulk/6493894dd9e8a7c3ad779c39c94dbe28 to your computer and use it in GitHub Desktop.
Save jtulk/6493894dd9e8a7c3ad779c39c94dbe28 to your computer and use it in GitHub Desktop.
React Hook to Create State and Syndicate to Local Storage
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