Imperative Focus in Event Handlers
You'll learn: How to programmatically focus an input or element directly inside event handlers like onClick or form submissions, using the ref you've already attached.
The Core Idea
Sometimes you need to focus an element in response to a user action—not on mount, but when they click a button, submit a form, or complete some task. This is where imperative focus in event handlers shines.
You've already learned to attach a ref to a DOM element and call ref.current.focus() in a useEffect to focus on mount. Now you'll do the same thing, but inside an event handler instead.
The Pattern
function SearchForm() {
const inputRef = useRef(null);
function handleClear() {
// Clear the form, then refocus the input
inputRef.current.value = '';
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleClear}>Clear</button>
</>
);
}
When the user clicks "Clear," the handleClear function runs. Inside it, you directly call inputRef.current.focus(). No useEffect needed—this is a direct response to an event.
Common Scenarios
- After form submission: refocus the input for another entry
- Error handling: focus the invalid field when validation fails
- Multi-step flows: move focus to the next input after completing one
- Modal dialogs: focus the first field when a modal opens via button click
Why Not useEffect?
Because the focus is caused by the event, not by a render or mount. Event handlers are the right place for imperative actions triggered by user interaction.
Key Takeaway: Call ref.current.focus() directly inside event handlers like onClick or onSubmit to imperatively focus elements in response to user actions.