import { ChangeEvent, ChangeEventHandler, useCallback, useState } from "react";

/** Track the value of the input without making the input controlled. */
export function useTrackedValue(
  onChange: ChangeEventHandler<HTMLInputElement> | undefined
) {
  const [value, setValue] = useState<string | undefined>(undefined);

  const takeValueSnapshot = useCallback(
    (element: HTMLInputElement | null) => setValue(element?.value),
    [setValue]
  );

  const handleChange = useCallback(
    (event: ChangeEvent<HTMLInputElement>) => {
      setValue(event.target.value);
      onChange?.(event);
    },
    [setValue, onChange]
  );

  return [value, takeValueSnapshot, handleChange] as const;
}
