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
javascript
import { useRef } from "react";
const myRef = useRef(null);myRefis an objectmyRef.currentholds the value- Updating
.currentdoes not re-render
š¹ 1. Accessing DOM Elements (Most Common Use)
Example: Focus Input
javascript
import { useRef } from "react";
function App() {
const inputRef = useRef(null);
return (
<>
>
);
}ā
Direct DOM access
ā No state needed
š¹ 2. Persist Value Without Re-render
Example: Render Counter
javascript
import { useRef, useState } from "react";
function App() {
const renderCount = useRef(0);
const [count, setCount] = useState(0);
renderCount.current++;
return (
<>
Count: {count}
Renders: {renderCount.current}
>
);
}ā renderCount updates
ā UI updates only when state changes
š¹ 3. Store Previous State Value
javascript
import { useRef, useEffect, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const prevCount = useRef(null);
useEffect(() => {
prevCount.current = count;
}, [count]);
return (
<>
Current: {count}
Previous: {prevCount.current}
>
);
}š¹ 4. Store Timers / Intervals (Interview Favorite)
javascript
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 (
<>
Time: {time}s
>
);
}ā 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.ā

