import { useState, useCallback } from 'react';

export default function<T>(defaultValue: T, storageKey: string | false) {
  const initialValueString = localStorage && storageKey && localStorage.getItem(storageKey);
  const initialValue = initialValueString ? JSON.parse(initialValueString) : defaultValue;
  const [value, setValue] = useState<T>(initialValue);
  const onSetValue = useCallback(
    (newValue: T) => {
      setValue(newValue);
      localStorage && storageKey && localStorage.setItem(storageKey, JSON.stringify(newValue));
    },
    [setValue, storageKey]
  );
  return [value, onSetValue] as [typeof value, typeof onSetValue];
}
