🚀 Mastering useRef in React – A Beginner's Guide

Frontend Developer | React & JavaScript Lover ⚛️ | Building cool web apps & sharing my learning journey 💻🚀
When you're learning React, one of the most confusing yet powerful hooks you’ll come across is useRef. I recently explored this concept during my React journey at Devsync, and here’s a simple explanation that helped me understand it better.
🔍 What is useRef?
useRef is a built-in React hook that helps you:
Access and interact with DOM elements directly.
Store mutable values without causing re-renders.
📦 How to Use useRef in React
First, import it:
import { useRef } from 'react';
✅ 1. Accessing DOM Elements
A common use case is focusing an input field:
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus(); // Focuses the input
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus</button>
</>
);
}
inputRef.currentpoints to the actual HTML element!
✅ 2. Keeping Mutable Values
Sometimes, you need to store a value that changes but doesn't cause a re-render.
import React, { useRef } from 'react';
function ClickCounter() {
const count = useRef(0);
const increment = () => {
count.current += 1;
console.log('Clicked:', count.current);
};
return <button onClick={increment}>Click Me</button>;
}
Unlike
useState, changingcount.currentwon’t re-render the component.
🧠 Why is useRef Useful?
| Feature | useRef |
| DOM access | ✅ Yes |
| Value persistence | ✅ Yes |
| Re-render on change | ❌ No |
💡 Final Thoughts
useRef might seem tricky at first, but once you get used to it, it becomes a valuable tool in your React toolkit. Thanks to Devsync, I was able to grasp it with ease and confidence.
If you're also on your learning journey, keep exploring and building — and remember, practice is key!
🔗 Useful Resources
React Official Docs – useRef