Question Bank
/

React Auto-Focus With Refs: Two Approaches Quiz

React Auto-Focus With Refs: Two Approaches Quiz

Two approaches to auto-focusing an input in React (`useRef` + `useEffect` vs the native `autoFocus` prop), plus companions on focusing after async state and on focusing inside a portal.

Question Bank
Medium
JavaScript
4 questions
quiz
react
references
hooks

1,030 views

28

Auto-focus a text input on mount using useRef and useEffect. Implement the focus call so the input receives focus exactly once, immediately after the first render.

Examples

Example 1:

Input: mount the component
Output (Rendered DOM + Effect): the text input gains focus right after the first paint; subsequent re-renders do not steal focus.
Explanation: useEffect with [] runs once after mount; calling .focus() on the ref's current node moves focus there.
import { useEffect, useRef } from 'react';

export default function FocusOnMount() {
    const inputRef = useRef(null);
    useEffect(() => {
        inputRef.current?.focus();
    }, []);
    return (
        <div>
            <button type="button" onClick={() => inputRef.current?.focus()}>
                Focus the text input
            </button>
            <input ref={inputRef} type="text" />
        </div>
    );
}