React Refs in Forms: Accessing DOM Elements

⚛️ Top 150 React Interview Questions – 48/150 📌 Topic: Refs in Forms 🔹 WHAT is it? A Ref (Reference) lets you access a DOM element directly in React. In forms, instead of tracking input values with state, you use a ref to read or control the input only when needed. 👉 React State = Declarative 👉 Refs = Imperative (direct DOM access) 🔹 WHY is it designed this way? React prefers state, but sometimes direct DOM access is required. ✅ Focus Management Auto-focus an input using .focus() (login, search, OTP forms) ✅ Performance Optimization Reading values via refs does not cause re-renders — great for large forms ✅ Native DOM Control Play/pause media, trigger animations, or read values instantly 🔹 HOW do you do it? (The Implementation) Use the useRef hook in Functional Components 👇 import { useRef } from "react"; function LoginForm() { const emailRef = useRef(null); const handleLogin = () => { const email = emailRef.current.value; console.log("Email:", email); if (!email) { emailRef.current.focus(); } }; return ( <> <input ref={emailRef} placeholder="Enter email" /> <button onClick={handleLogin}>Login</button> </> ); } 🔹 WHERE are the best practices? ✔ Use refs for focus, text selection, animations, and uncontrolled forms ✔ File inputs are always uncontrolled → refs required ❌ Don’t replace state with refs everywhere ❌ Never use document.getElementById() in React — use useRef 📝 Summary for your notes A Ref is like a Laser Pointer 🔦 Instead of announcing to the whole room (state change), you point directly to the exact element (DOM) and control it. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #LearningInPublic #Top150ReactQuestions

  • text

To view or add a comment, sign in

Explore content categories