Accessing DOM Elements With useRef
0 490
🔍 What Is useRef in React?
useRef is a built-in React Hook that allows you to persist values across renders without causing re-renders. One of its most common uses is to access and interact directly with DOM elements. 🧠⚙️
📦 Why Access DOM Elements Directly?
Sometimes, you need to manipulate or focus on DOM elements manually — especially when working with:
- 🧭 Managing focus (e.g., input fields)
- 🎥 Controlling media elements (e.g., video, audio)
- 📏 Measuring element size or position
- 🎨 Direct animations or styling without re-rendering
useRef becomes incredibly useful.
🔗 How to Create a DOM Reference with useRef
Let’s see how to create and attach a ref to a DOM element:
import { useRef, useEffect } from 'react';
function TextInputFocus() {
const inputRef = useRef(null); // Step 1: Create the ref
useEffect(() => {
inputRef.current.focus(); // Step 3: Access and focus the input
}, []);
return (
<input ref={inputRef} placeholder="Auto-focus input" /> // Step 2: Attach the ref
);
}
💡 inputRef.current gives you direct access to the actual DOM element, similar to document.querySelector.
🎥 Example: Controlling a Video Element
function VideoPlayer() {
const videoRef = useRef(null);
const playVideo = () => videoRef.current.play();
const pauseVideo = () => videoRef.current.pause();
return (
<div>
<video ref={videoRef} width="300" src="video.mp4" />
<button onClick={playVideo}>Play</button>
<button onClick={pauseVideo}>Pause</button>
</div>
);
}
🎯 With useRef, you're directly controlling the media without needing to re-render the component.
🧱 useRef vs useState: Key Differences
| useRef | useState |
| Does not trigger re-renders | Triggers re-renders on update |
| Used for accessing DOM elements or persisting mutable values | Used for reactive state |
.current property holds the value | Setter updates and causes re-render |
🔁 Persisting Values Without Re-rendering
You can also use useRef to store values that need to persist across renders but don’t require a re-render when changed:
function Stopwatch() {
const count = useRef(0);
useEffect(() => {
const interval = setInterval(() => {
count.current += 1;
console.log(count.current);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Open console to see count ⏱️</p>;
}
🧠 Perfect for intervals, timers, or mutable values that shouldn’t affect the UI.
🧠 Best Practices
- ✅ Use
useReffor DOM access and storing mutable data - ❌ Don’t use it to replace
useStatefor UI-driven state - ✅ Always check
ref.currentbefore accessing methods or properties
🚀 Final Thoughts
The useRef hook is your go-to tool for accessing DOM elements directly in React. From focusing inputs to controlling videos or storing values outside the render cycle — it brings flexibility to your functional components without side effects. Master it, and your React skills will level up fast! 💪🔥
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments