useAutoFocus

All about useAutoFocus hook in React


A React hook to automatically focus an element (e.g., <input> or <textarea>) when the component mounts.
It can also optionally re-focus when dependencies change.

LinkIconUsage

import React, { useRef } from "react";
import { useAutoFocus } from "./useAutoFocus";
 
export function LoginForm() {
 
  const ref = useAutoFocus({ delay: 300 });
 
  return (
    <form>
      <label htmlFor="username">Username</label>
      <input ref={ref} id="username" type="text" />
    </form>
  );
}

LinkIconHook

import { RefObject, useEffect } from "react";
 
interface UseAutoFocusOptions {
  /** Delay in milliseconds before focusing */
  delay?: number;
  /** Dependencies to re-run the focus effect */
  deps?: unknown[];
}
 
/**
 * Automatically focuses the given element when mounted or when dependencies change.
 * @returns A ref to assign to the focusable element.
 */
export function useAutoFocus<T extends HTMLElement>(
  options: UseAutoFocusOptions = {}
) {
  const { delay = 0, dependencies = [] } = options;
  const ref = useRef<T>(null);
 
  const handleButtonClick = () => {
    ref.current.focus();
  };
 
  useEffect(() => {
    const timer = setTimeout(handleButtonClick, delay);
 
    return () => clearTimeout(timer);
  }, [delay, ...dependencies])
 
  return { ref }
}

LinkIconParameters

NameTypeDefaultDescription
options{ delay?: number; dependencies?: unknown[] }{}Optional configuration object.
options.delaynumber0Delay in milliseconds before focusing. Useful for animations or mounted transitions.
options.dependenciesunknown[][]Dependencies that trigger re-focusing when they change.

LinkIconReturns

NameTypeDescription
refRefObject<T>A React ref to assign to the focusable DOM element.