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.
Usage
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>
);
}
Hook
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 }
}
Parameters
Name | Type | Default | Description |
---|---|---|---|
options | { delay?: number; dependencies?: unknown[] } | {} | Optional configuration object. |
options.delay | number | 0 | Delay in milliseconds before focusing. Useful for animations or mounted transitions. |
options.dependencies | unknown[] | [] | Dependencies that trigger re-focusing when they change. |
Returns
Name | Type | Description |
---|---|---|
ref | RefObject<T> | A React ref to assign to the focusable DOM element. |