Skip to content

Instantly share code, notes, and snippets.

@jogilvyt
Created January 19, 2021 16:35
Show Gist options
  • Save jogilvyt/4ed46083697abc44d904013b698fffb3 to your computer and use it in GitHub Desktop.
Save jogilvyt/4ed46083697abc44d904013b698fffb3 to your computer and use it in GitHub Desktop.
React hook to store state in localStorage
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