import { useRef, type RefObject } from 'react'

/**
 * Works like `useRef` but accepts an initializer function that runs once on the first render, like
 * `useState`.
 */
export function useRefWithInit<T>(initFn: () => T) {
  const ref = useRef<T | undefined>(undefined)

  if (ref.current === undefined) {
    ref.current = initFn()
  }

  return ref as RefObject<T>
}
