DEV Community

Cover image for Using `useRef` to Set Focus on an Input Field
Bishoy Bishai
Bishoy Bishai

Posted on • Edited on • Originally published at bishoy-bishai.github.io

Using `useRef` to Set Focus on an Input Field

We’ve all been there—you click "Edit" and... nothing. You have to click the input field yourself like it’s 2005. That is a Cramp in the user experience!

In a perfect Bachata flow, the leader moves and the partner follows instantly. In React, useRef is how we lead the user's attention without them having to hunt for the "ball."

⚽ Why Focus is Your "Home Advantage"

If you are playing Football, you want the ball exactly where your striker is running. You don't want them searching for it in the grass.

  • Workflow Efficiency: No more "search and click."
  • Accessibility (a11y): It's like a clear whistle from the referee—everyone knows what’s happening.
  • Error Handling: If there's a Red Card (validation error), jump the focus to the mistake immediately!

💃 The Technique: useRef in Action

React is usually "declarative"—we tell it what we want, and it does the work. But sometimes, we need to be "imperative." We need to grab the DOM node and say, "Hey! Focus now!"

Here is how we do the "Perfect Lead":

import React, { useRef, useEffect, useState } from 'react';

const SmoothFocusInput = () => {
  // 1. Create the reference (The "Lead")
  const inputRef = useRef<HTMLInputElement>(null);
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    // 2. The "1, 2, 3, Tap!" logic
    if (isEditing && inputRef.current) {
      inputRef.current.focus(); 
      // Boom! The cursor is exactly where it belongs.
    }
  }, [isEditing]);

  return (
    <div>
      {isEditing ? (
        <input 
          ref={inputRef} // 3. Connect the reference to the pitch
          type="text" 
          placeholder="Type like a pro..." 
        />
      ) : (
        <button onClick={() => setIsEditing(true)}>
          Edit Profile 
        </button>
      )}
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

🚩 Avoid the "Red Cards" (Common Mistakes)

Trust me, I’ve seen these mistakes more than I’ve seen bad referee calls:

  1. The "Empty Pass": Trying to use inputRef.current before it exists. Always check if it's there before calling .focus().
  2. Focusing Too Early: If you try to focus during the render phase, the "pitch" isn't even ready yet. Always use useEffect.
  3. Over-Engineering: Don't use useRef for everything. If a simple autoFocus prop works for a page load, use it! Save the useRef for the dynamic moves.

🕺 Summary of the Moves

Step The Bachata Way The React Way
Preparation Get in position useRef(null)
Connection Hold your partner's hand ref={inputRef}
The Lead Signal the next move useEffect with [dependency]
The Finish 1, 2, 3, Tap! inputRef.current.focus()

💡 Pro Tip from the Pitch

Combine focus with selection! If you are editing an existing value, don't just .focus(). Use inputRef.current.select(). This highlights all the text so the user can start typing over it immediately. It’s like a perfect through-ball right to the striker's feet.

Would you like me to show you how to handle focus across a whole list of inputs? I can show you how to manage multiple refs without breaking a sweat!


✨ Let's keep the conversation going!

If you found this interesting, I'd love for you to check out more of my work or just drop in to say hello.

✍️ Read more on my blog: bishoy-bishai.github.io

Let's chat on LinkedIn: linkedin.com/in/bishoybishai

📘 Curious about AI?:
You can also check out my book: Surrounded by AI


Top comments (0)