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