useRef – Access DOM Elements & Store Mutable Values
✅ What is useRef
?
In React, useRef
is a special hook that lets you:
1. Access and interact with DOM elements
👉 Like document.getElementById()
in plain JS
2. Store mutable values (like a variable) that don’t cause re-renders
👉 Great for timers, counters, caching, etc.
📦 Syntax:
const refName = useRef(initialValue);
🧪 Example 1: Accessing a DOM Element
import React, { useRef } from "react";
function InputFocus() {
const inputRef = useRef();
const handleClick = () => {
inputRef.current.focus(); // focuses input
};
return (
<div>
<input ref={inputRef} type="text" placeholder="Click the button to focus me" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
export default InputFocus;
inputRef
refers to the input DOM node
inputRef.current
is the actual input element
You can call methods like .focus()
, .value
, .scrollIntoView()
etc.
🧪 Example 2: Store Value Without Re-render
import React, { useRef, useState, useEffect } from "react";
function CountRenders() {
const [count, setCount] = useState(0);
const renders = useRef(1);
useEffect(() => {
renders.current++;
});
return (
<div>
<h2>Count: {count}</h2>
<h4>Rendered {renders.current} times</h4>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
renders
keeps track of how many times the component re-rendered- We use
.current
to update the value without causing re-renders
Keep Learning 🙂