Created
Feb 4, 2026Last Modified
2 months agoUse of ref
What is ref in React?
A ref is a way to directly access a DOM element or store a mutable value that does NOT cause re-render when it changes.
In modern React, we use useRef.
🔹 Basic Syntax
import { useRef } from "react";
const myRef = useRef(null);myRefis an objectmyRef.currentholds the valueUpdating
.currentdoes not re-render
🔹 1. Accessing DOM Elements (Most Common Use)
Example: Focus Input
import { useRef } from "react";
function App() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus Input
</button>
</>
);
}✅ Direct DOM access
❌ No state needed
🔹 2. Persist Value Without Re-render
Example: Render Counter
import { useRef, useState } from "react";
function App() {
const renderCount = useRef(0);
const [count, setCount] = useState(0);
renderCount.current++;
return (
<>
<p>Count: {count}</p>
<p>Renders: {renderCount.current}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</>
);
}✔ renderCount updates
✔ UI updates only when state changes
🔹 3. Store Previous State Value
import { useRef, useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const prevCount = useRef(null);
useEffect(() => {
prevCount.current = count;
}, [count]);
return (
<>
<p>Current: {count}</p>
<p>Previous: {prevCount.current}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</>
);
}🔹 4. Store Timers / Intervals (Interview Favorite)
import { useRef, useState } from "react";
function Stopwatch() {
const timerRef = useRef(null);
const [time, setTime] = useState(0);
const start = () => {
if (!timerRef.current) {
timerRef.current = setInterval(() => {
setTime(t => t + 1);
}, 1000);
}
};
const stop = () => {
clearInterval(timerRef.current);
timerRef.current = null;
};
return (
<>
<p>Time: {time}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</>
);
}✔ Interval persists across renders
✔ No unwanted re-renders
🔹 5. useState vs useRef (Core Difference)
Feature | useState | useRef |
|---|---|---|
Triggers re-render | ✅ | ❌ |
DOM access | ❌ | ✅ |
Store mutable value | ❌ | ✅ |
UI update | ✅ | ❌ |
🔹 When NOT to Use ref
❌ For displaying data in UI
❌ For main application state
❌ As replacement for state
Rule:
UI change →useState
Logic / DOM / memory →useRef
🔹 One-Line Interview Answer
“
useReflets us access DOM elements and store mutable values that persist across renders without causing re-render.”
