import { useCallback, useRef } from "react";

/** Keeps React keys stable when optimistic temp ids become server ids */
export function useStableMessageKeys() {
  const aliasRef = useRef(new Map<string, string>());

  const linkIds = useCallback((tempId: string, realId: string) => {
    aliasRef.current.set(realId, tempId);
    aliasRef.current.set(tempId, tempId);
  }, []);

  const getStableKey = useCallback((id: string) => {
    return aliasRef.current.get(id) ?? id;
  }, []);

  return { linkIds, getStableKey };
}
