useSessionStorage.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import {Dispatch, SetStateAction, useEffect, useState} from 'react';
  2. const isBrowser = typeof window !== 'undefined';
  3. function useSessionStorage<T>(
  4. key: string,
  5. initialValue?: T
  6. ): [T | undefined, Dispatch<SetStateAction<T | undefined>>, () => void] {
  7. const [state, setState] = useState<T | undefined>(() => {
  8. try {
  9. // Get from session storage by key
  10. const sessionStorageValue = sessionStorage.getItem(key);
  11. if (sessionStorageValue === 'undefined') {
  12. return initialValue;
  13. }
  14. // Parse stored json or if none return initialValue
  15. return sessionStorageValue ? JSON.parse(sessionStorageValue) : initialValue;
  16. } catch {
  17. // If user is in private mode or has storage restriction
  18. // sessionStorage can throw. JSON.parse and JSON.stringify
  19. // can throw, too.
  20. return initialValue;
  21. }
  22. });
  23. useEffect(() => {
  24. try {
  25. const serializedState = JSON.stringify(state);
  26. sessionStorage.setItem(key, serializedState);
  27. } catch {
  28. // If user is in private mode or has storage restriction
  29. // sessionStorage can throw. Also JSON.stringify can throw.
  30. }
  31. }, [state]);
  32. function removeItem() {
  33. sessionStorage.removeItem(key);
  34. setState(undefined);
  35. }
  36. if (!isBrowser) {
  37. return [initialValue, () => {}, () => {}];
  38. }
  39. return [state, setState, removeItem];
  40. }
  41. export default useSessionStorage;