import { useEffect, useRef } from 'react' export const useAutoFocus = (autoFocus?: boolean) => { const ref = useRef(null) useEffect(() => { if (!autoFocus || !ref.current) return const attemptFocus = (attempts = 0): void => { if (attempts > 20 || !ref.current) return const focusable = ref.current.querySelector( 'button:not([disabled]), [tabindex]:not([tabindex="-1"])' ) if (focusable) { focusable.focus() } else { requestAnimationFrame(() => attemptFocus(attempts + 1)) } } requestAnimationFrame(() => attemptFocus()) }, [autoFocus]) return ref }