Question Bank

React Auto-Focus With Refs: Two Approaches Quiz

Difficulty: Medium

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
/

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,029 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.