Skip to content

Instantly share code, notes, and snippets.

@dschep
Created August 16, 2020 18:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dschep/52f6eb1e0582c9df5a81207a60ecb947 to your computer and use it in GitHub Desktop.
Save dschep/52f6eb1e0582c9df5a81207a60ecb947 to your computer and use it in GitHub Desktop.
import { useState } from "react";
const useLocalStorageState = (storageKey, defaultValue) => {
const [value, setValue] = useState(
JSON.parse(localStorage.getItem(storageKey) || "null") || defaultValue
);
const wrappedSetValue = (newValue) => {
localStorage.setItem(storageKey, JSON.stringify(newValue));
setValue(newValue);
};
return [value, wrappedSetValue];
};
export default useLocalStorageState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment