import { useState, useEffect } from 'react';

const useSessionStorage = (key: string) => {
  const [state, setState] = useState(() => {
    try {
      const localStorageValue = sessionStorage.getItem(key);
      return JSON.parse(localStorageValue || 'null');
    } catch (error) {
      console.error(error);
    }
  });

  useEffect(() => {
    try {
      const serializedState = JSON.stringify(state);
      sessionStorage.setItem(key, serializedState);
    } catch (error) {
      console.error(error);
    }
  }, [state]);

  return [state, setState];
};

export default useSessionStorage;
