useLocalStorage.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import React from "react";
  2. const useLocalStorage = (key, initialValue) => {
  3. // State to store our value
  4. const [storedValue, setStoredValue] = React.useState(() => {
  5. try {
  6. // Get from local storage by key
  7. const item = window.localStorage.getItem(key);
  8. if (!item) {
  9. // If missing we add it
  10. window.localStorage.setItem(key, JSON.stringify(initialValue));
  11. return initialValue;
  12. }
  13. return JSON.parse(item);
  14. } catch (error) {
  15. // If error also return initialValue
  16. console.log(error);
  17. return initialValue;
  18. }
  19. });
  20. // Return a wrapped version of useState's setter function that ...
  21. // ... persists the new value to localStorage.
  22. const setValue = (value) => {
  23. try {
  24. // Allow value to be a function so we have same API as useState
  25. const valueToStore =
  26. value instanceof Function ? value(storedValue) : value;
  27. // Save state
  28. setStoredValue(valueToStore);
  29. // Save to local storage
  30. window.localStorage.setItem(key, JSON.stringify(valueToStore));
  31. } catch (error) {
  32. // A more advanced implementation would handle the error case
  33. console.log(error);
  34. }
  35. };
  36. React.useEffect(() => {
  37. const localStorageChanged = (e) => {
  38. if (e.key === key) {
  39. setStoredValue(JSON.parse(e.newValue));
  40. }
  41. };
  42. window.addEventListener("storage", localStorageChanged);
  43. return () => {
  44. window.removeEventListener("storage", localStorageChanged);
  45. };
  46. }, [key]);
  47. return [storedValue, setValue];
  48. };
  49. export default useLocalStorage;