use-local-storage.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use client"
  2. import React from "react";
  3. const useLocalStorage = <T>(key: string, initialValue: T) => {
  4. // State to store our value
  5. // Pass initial state function to useState so logic is only executed once
  6. const [storedValue, setStoredValue] = React.useState<T>(() => {
  7. if (typeof window === "undefined") {
  8. return initialValue
  9. }
  10. try {
  11. // Get from local storage by key
  12. const item = window.localStorage.getItem(key)
  13. // Parse stored json or if none return initialValue
  14. return item ? JSON.parse(item) : initialValue
  15. } catch (error) {
  16. // If error also return initialValue
  17. console.log(error)
  18. return initialValue
  19. }
  20. })
  21. // Return a wrapped version of useState's setter function that ...
  22. // ... persists the new value to localStorage.
  23. const setValue = (value: T | ((val: T) => T)) => {
  24. try {
  25. // Allow value to be a function so we have same API as useState
  26. const valueToStore =
  27. value instanceof Function ? value(storedValue) : value;
  28. // Save state
  29. setStoredValue(valueToStore);
  30. // Save to local storage
  31. if (typeof window !== "undefined") {
  32. window.localStorage.setItem(key, JSON.stringify(valueToStore));
  33. }
  34. } catch (error) {
  35. // A more advanced implementation would handle the error case
  36. console.log(error);
  37. }
  38. };
  39. return [storedValue, setValue] as const;
  40. }
  41. export default useLocalStorage