import { useEffect, useState } from 'react';

export const useLocalStorage = <T extends string>(
  key: string,
  defaultValue: T,
): [T, (value: T) => void] => {
  const localValueOrDefault: T = (localStorage.getItem(key) ??
    defaultValue) as T;

  const [localValue, setLocalValue] = useState<T>(localValueOrDefault);

  useEffect(() => {
    localStorage.setItem(key, localValue);
  }, [localValue, key]);

  return [localValue, setLocalValue];
};
