1. What is useRef in React?
useRef is a React Hook used to store a value that survives between renders without causing a re-render, or to directly access a DOM element.
It is commonly used for two major purposes:
- Accessing DOM elements
- Storing mutable values between renders
const ref = useRef(initialValue);
React returns an object like:
{
current: initialValue
}
You access the value through:
ref.current
The most important idea is:
Changing
ref.currentdoes NOT cause the component to re-render.
2. Why do we need useRef?
Normally, React state is used when changing a value should update the UI.
const [count, setCount] = useState(0);
When you do:
setCount(10);
React schedules a re-render.
But sometimes you need to remember a value without updating the UI.
For example:
Previous render value
Timer ID
DOM element
Input element
Interval ID
WebSocket connection
Third-party library instance
Latest value
For these situations, useRef can be useful.
useState vs useRef
useState
|
+-- value changes
|
+-- React re-renders
|
+-- UI can update
useRef
|
+-- ref.current changes
|
+-- React does NOT re-render
|
+-- useful for persistent/mutable values
3. Basic syntax
import { useRef } from "react";
const myRef = useRef(initialValue);
Example:
const countRef = useRef(0);
Initially:
countRef.current = 0
You can change it:
countRef.current = 10;
Now:
countRef.current = 10
But React does not re-render the component because of this change.
4. How does useRef work?
Consider:
const countRef = useRef(0);
React creates a ref object:
countRef
|
+--- current: 0
If you execute:
countRef.current = 100;
it becomes:
countRef
|
+--- current: 100
The important part is that the same ref object is preserved between renders.
For example:
Render 1
|
+-- countRef.current = 0
|
v
User clicks
|
+-- countRef.current = 1
|
v
Render happens for some other reason
|
+-- countRef.current is still 1
So useRef provides persistent storage inside a component.
5. The two main uses of useRef
Almost everything you do with useRef falls into these categories.
Use 1 — Accessing DOM elements
const inputRef = useRef<HTMLInputElement>(null);
<input ref={inputRef} />
Then:
inputRef.current?.focus();
Use 2 — Storing a value between renders
const countRef = useRef(0);
countRef.current++;
The value survives renders, but changing it doesn't cause another render.
6. Basic DOM example — focus an input
This is probably the most common beginner example.
import { useRef } from "react";
function App() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
inputRef.current?.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={focusInput}>
Focus Input
</button>
</div>
);
}
export default App;
Flow
<input ref={inputRef} />
|
v
React connects DOM element
to inputRef.current
|
v
inputRef.current
|
v
HTMLInputElement
|
v
inputRef.current.focus()
|
v
Input receives focus
Result
When the user clicks:
Focus Input
the cursor moves into the input.
7. Why can useRef access the DOM?
When React renders:
<input ref={inputRef} />
React assigns the actual DOM element to:
inputRef.current
Conceptually:
inputRef
|
+-- current
|
+-- <input DOM element>
For a DOM element, current is populated after React has committed the element to the DOM.
When the component is unmounted, React will clear the DOM ref.
8. useRef does not trigger a re-render
This is one of the most important interview points.
Consider:
function App() {
const countRef = useRef(0);
const increase = () => {
countRef.current++;
console.log(countRef.current);
};
return (
<button onClick={increase}>
Count: {countRef.current}
</button>
);
}
You might expect:
Count: 1
Count: 2
Count: 3
But the UI will not update.
Why?
Because:
countRef.current++;
doesn't tell React to render again.
The console may show:
1
2
3
while the screen remains:
Count: 0
Correct approach
If the value needs to appear in the UI:
const [count, setCount] = useState(0);
Use useState for UI state.
9. useState vs useRef
| Feature | useState |
useRef |
|---|---|---|
| Stores value | Yes | Yes |
| Survives renders | Yes | Yes |
| Changing value causes render | Yes | No |
| Access DOM | No | Yes |
| Mutable | Update through setter | Directly mutable |
| Used for UI state | Yes | Usually no |
| Stores timer ID | Possible, but usually unnecessary | Yes |
| Stores previous value | Possible | Very useful |
Simple rule
If changing the value should update the screen, use
useState.
If the value needs to persist but changing it should not update the screen, consider
useRef.
10. Use useRef to count renders
A useful example for understanding useRef:
import { useEffect, useRef, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const renderCount = useRef(0);
renderCount.current++;
return (
<div>
<p>Count: {count}</p>
<p>Render count: {renderCount.current}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
Here:
setCount(...)
causes rendering.
During each render:
renderCount.current++;
updates the ref.
The important idea is that the ref remembers its value across renders.
Important caution
Using a ref during render for diagnostic purposes like this can be misleading in development, especially with React Strict Mode. For production logic, don't use render counters as though every function execution corresponds exactly to a committed browser update.
11. Use useRef to store the previous value
This is a very common practical pattern.
Suppose:
count = 10
and then:
count = 20
You want to know the previous value.
import { useEffect, useRef, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const previousCount = useRef<number | undefined>(undefined);
useEffect(() => {
previousCount.current = count;
}, [count]);
return (
<div>
<p>Current: {count}</p>
<p>Previous: {previousCount.current}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
Data flow
Initially:
count = 0
previousCount.current = undefined
After changing count:
count = 1
The component renders.
Then:
useEffect()
|
+-- previousCount.current = 1
On the next update, the ref contains the previous committed value.
Why useRef?
Because the value needs to survive the next render, but it doesn't need to independently cause another render.
12. Focus the input after rendering
Another common pattern is focusing an input when the component loads.
import { useEffect, useRef } from "react";
function App() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} />;
}
Flow
Component renders
|
v
<input> is created
|
v
React assigns DOM element
to inputRef.current
|
v
useEffect runs
|
v
inputRef.current.focus()
|
v
Input receives focus
This is a good example of using:
useRef + useEffect
13. Scroll to an element
useRef is very useful for scrolling.
import { useRef } from "react";
function App() {
const sectionRef = useRef<HTMLDivElement>(null);
const scrollToSection = () => {
sectionRef.current?.scrollIntoView({
behavior: "smooth",
});
};
return (
<div>
<button onClick={scrollToSection}>
Go to Section
</button>
<div style={{ height: "1000px" }} />
<div ref={sectionRef}>
<h2>Target Section</h2>
<p>You have reached the target.</p>
</div>
</div>
);
}
Real-world usage
This pattern is common for:
- FAQ pages
- Landing pages
- Navigation menus
- Checkout steps
- Long forms
- Documentation pages
14. Scroll to the latest chat message
This is a realistic example.
import { useEffect, useRef, useState } from "react";
function Chat() {
const [messages, setMessages] = useState<string[]>([]);
const bottomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
bottomRef.current?.scrollIntoView({
behavior: "smooth",
});
}, [messages]);
const addMessage = () => {
setMessages(prev => [
...prev,
`Message ${prev.length + 1}`,
]);
};
return (
<div>
<div>
{messages.map((message, index) => (
<p key={index}>{message}</p>
))}
<div ref={bottomRef} />
</div>
<button onClick={addMessage}>
Add Message
</button>
</div>
);
}
The invisible div acts as the target.
Message 1
Message 2
Message 3
Message 4
[bottomRef]
When a new message is added:
messages changes
|
v
component renders
|
v
useEffect runs
|
v
bottomRef.current
|
v
scrollIntoView()
15. Accessing multiple DOM elements
You can have multiple refs.
const nameRef = useRef<HTMLInputElement>(null);
const emailRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
Then:
<input ref={nameRef} />
<input ref={emailRef} />
<input ref={passwordRef} />
You can control each independently:
nameRef.current?.focus();
or:
emailRef.current?.focus();
16. Managing form focus
Suppose a user submits an empty form.
You can focus the first invalid field.
function Form() {
const nameRef = useRef<HTMLInputElement>(null);
const submit = () => {
const name = nameRef.current?.value;
if (!name) {
nameRef.current?.focus();
return;
}
};
return (
<form>
<input ref={nameRef} />
<button type="button" onClick={submit}>
Submit
</button>
</form>
);
}
This is useful for:
- Validation
- Login forms
- Registration
- Checkout
- Search forms
17. Reading an input value using useRef
You can access the DOM value directly.
import { useRef } from "react";
function App() {
const inputRef = useRef<HTMLInputElement>(null);
const showValue = () => {
console.log(inputRef.current?.value);
};
return (
<>
<input ref={inputRef} />
<button onClick={showValue}>
Get Value
</button>
</>
);
}
If the user enters:
Syed
then:
inputRef.current?.value
returns:
Syed
But should you always do this?
No.
For most React forms, controlled inputs using useState are preferred when the UI needs to react to input changes.
18. Controlled vs uncontrolled input
This is an important React concept.
Controlled input
React state controls the value.
const [name, setName] = useState("");
<input
value={name}
onChange={e => setName(e.target.value)}
/>
Flow:
User types
|
v
onChange
|
v
setName()
|
v
React state changes
|
v
Component renders
|
v
Input value updates
Uncontrolled input
The DOM manages the value.
const nameRef = useRef<HTMLInputElement>(null);
<input ref={nameRef} />
Then:
nameRef.current?.value
gets the current value.
Comparison
| Controlled | Uncontrolled |
|---|---|
useState |
useRef / DOM |
| React controls value | DOM controls value |
| Every change can trigger render | Typing doesn't require React render |
| Easier for dynamic UI | Useful for simple forms |
| Common React approach | Useful in specific scenarios |
19. Store a timer ID
Another very common use of useRef is storing a timer ID.
import { useRef } from "react";
function Timer() {
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const start = () => {
timerRef.current = setInterval(() => {
console.log("Running...");
}, 1000);
};
const stop = () => {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
};
return (
<>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</>
);
}
Why useRef?
The timer ID needs to survive between renders.
But the timer ID itself does not need to appear in the UI.
Therefore:
Timer ID → useRef
is appropriate.
20. useRef with setTimeout
Example:
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
You can store the timeout:
timeoutRef.current = setTimeout(() => {
console.log("Hello");
}, 2000);
And cancel it:
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
This is useful for:
- Debouncing
- Delayed actions
- Auto-hide messages
- Notifications
- Cleanup
21. useRef for debouncing
For example, delaying an API call until the user stops typing:
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleSearch = (value: string) => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
console.log("Call API for:", value);
}, 500);
};
Flow
User types "R"
|
+-- start timer
User types "Re"
|
+-- cancel previous timer
+-- start new timer
User types "React"
|
+-- cancel previous timer
+-- start new timer
User stops typing
|
+-- 500ms passes
|
+-- API call
This is a very practical useRef pattern.
22. Store a mutable value that doesn't affect UI
Suppose you need to keep track of whether something has happened.
const hasLoadedRef = useRef(false);
Later:
hasLoadedRef.current = true;
The value persists.
But:
hasLoadedRef.current = true;
doesn't cause rendering.
This makes refs useful for internal bookkeeping.
23. useRef with useEffect
useRef and useEffect are often used together.
For example:
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
Here:
useRef
|
+-- gives access to DOM element
|
v
useEffect
|
+-- performs side effect
|
v
focus()
A useful rule:
useRefgives you the persistent reference;useEffectis often where you perform an action involving that reference after rendering.
24. useRef with useEffect for previous values
This is another common combination:
const previousValue = useRef(value);
useEffect(() => {
previousValue.current = value;
}, [value]);
The effect updates the ref after the render.
Therefore the next render can access the previous value.
25. useRef with useState
You can use both together.
const [count, setCount] = useState(0);
const previousCount = useRef(0);
State controls the UI:
setCount(count + 1);
Ref stores information about the previous state:
useEffect(() => {
previousCount.current = count;
}, [count]);
Conceptually:
useState
|
+-- UI state
|
+-- causes render
useRef
|
+-- persistent internal value
|
+-- doesn't cause render
They solve different problems.
26. Store the latest value
A ref can be used to keep the latest value accessible from a callback.
Example:
function App() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
useEffect(() => {
countRef.current = count;
}, [count]);
return (
<button onClick={() => setCount(c => c + 1)}>
{count}
</button>
);
}
The ref can provide the latest value to code that needs a persistent mutable reference.
However, don't automatically reach for this pattern whenever you see a closure issue. In modern React, first consider whether your effect dependencies, functional state updates, or event-handler structure can solve the problem more simply.
27. useRef and stale closures
This is an intermediate/advanced topic.
Consider:
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
console.log(count);
}, 1000);
return () => clearInterval(id);
}, []);
The callback can retain the count value from the render that created the effect.
A ref can provide a mutable reference to the latest value:
const countRef = useRef(count);
useEffect(() => {
countRef.current = count;
}, [count]);
Then another long-lived callback can read:
countRef.current
This is useful when integrating with:
- Timers
- Event listeners
- WebSockets
- Browser APIs
- Third-party libraries
But again, use the simplest solution appropriate to the situation.
28. useRef with event listeners
Suppose you register a browser event listener.
useEffect(() => {
const handleResize = () => {
console.log(window.innerWidth);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
If the handler needs the latest changing value, a ref can sometimes help:
const valueRef = useRef(value);
useEffect(() => {
valueRef.current = value;
}, [value]);
Then:
console.log(valueRef.current);
can access the latest stored value.
This is especially useful when you want to avoid repeatedly registering and removing an external event listener just because a value changed.
29. useRef with third-party libraries
This is one of the most important real-world uses.
Suppose you integrate a JavaScript library that needs a DOM element:
const containerRef = useRef<HTMLDivElement>(null);
<div ref={containerRef} />
Then:
useEffect(() => {
if (!containerRef.current) return;
// Initialize third-party library
}, []);
Conceptually:
React
|
v
<div ref={containerRef}>
|
v
DOM element
|
v
Third-party JavaScript library
This pattern is commonly used with:
- Charts
- Maps
- Rich text editors
- Video players
- Animation libraries
- Canvas libraries
- Code editors
30. Example: Canvas with useRef
import { useEffect, useRef } from "react";
function CanvasExample() {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.fillRect(20, 20, 100, 100);
}, []);
return (
<canvas
ref={canvasRef}
width={300}
height={200}
/>
);
}
React creates the canvas.
useRef gives you access to the actual DOM canvas.
Then normal JavaScript APIs manipulate it.
31. Example: Video control
import { useRef } from "react";
function VideoPlayer() {
const videoRef = useRef<HTMLVideoElement>(null);
const playVideo = () => {
videoRef.current?.play();
};
const pauseVideo = () => {
videoRef.current?.pause();
};
return (
<div>
<video ref={videoRef} controls>
<source src="/video.mp4" />
</video>
<button onClick={playVideo}>
Play
</button>
<button onClick={pauseVideo}>
Pause
</button>
</div>
);
}
Here React isn't managing the video's playback state directly.
The browser's video element does that.
useRef provides access to the element.
32. Example: File input
A file input is another useful scenario.
import { useRef } from "react";
function FileUpload() {
const fileInputRef = useRef<HTMLInputElement>(null);
const selectFile = () => {
fileInputRef.current?.click();
};
return (
<div>
<input
ref={fileInputRef}
type="file"
hidden
/>
<button onClick={selectFile}>
Select File
</button>
</div>
);
}
Flow
User clicks button
|
v
fileInputRef.current.click()
|
v
Browser opens file picker
This is a very common real-world use.
33. Example: Detecting whether an element exists
You can check:
if (elementRef.current) {
// Element exists
}
For example:
useEffect(() => {
if (sectionRef.current) {
console.log("Element exists");
}
}, []);
This is useful when working with DOM APIs.
34. Callback refs
There is another way to work with refs: callback refs.
Instead of:
const inputRef = useRef<HTMLInputElement>(null);
<input ref={inputRef} />
you can do:
<input
ref={(element) => {
console.log(element);
}}
/>
React calls the function when the ref is attached or detached.
Callback refs are useful when:
- You need custom ref behavior
- The referenced element changes dynamically
- You need to perform logic when an element becomes available
For normal DOM access, however, useRef is usually simpler.
35. Forwarding refs
Sometimes a parent needs access to a DOM element inside a child component.
For example:
Parent
|
v
Child
|
v
<input>
The parent may want to focus the child's input.
This is where ref forwarding comes into play.
In modern React, React 19 changed the ref model so that function components can receive ref as a prop, making many traditional forwardRef use cases simpler.
A simplified React 19-style example is:
type InputProps = {
ref?: React.Ref<HTMLInputElement>;
};
function CustomInput({ ref }: InputProps) {
return <input ref={ref} />;
}
Parent:
function App() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<>
<CustomInput ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>
Focus
</button>
</>
);
}
The important concept is:
Parent ref
|
v
Child receives ref
|
v
Child attaches ref to input
|
v
Parent can access input
36. useImperativeHandle
For advanced component APIs, useImperativeHandle can expose a limited set of operations through a ref.
For example, instead of exposing the entire DOM element, a child can expose:
focus()
clear()
Conceptually:
Parent
|
| ref
v
Child
|
+-- focus()
+-- clear()
This is useful for reusable components such as:
- Custom input components
- Video players
- Rich text editors
- Complex UI controls
It should be used carefully because it creates an imperative API between components.
37. useRef with forwardRef — older/common pattern
You may encounter code like:
const CustomInput = forwardRef<HTMLInputElement>((props, ref) => {
return <input ref={ref} />;
});
This is the traditional pattern used in React versions before the React 19 ref changes.
If you're learning modern React, understand both patterns because existing production applications may use forwardRef.
38. useRef with arrays
Sometimes you need refs for multiple elements.
For example:
Item 1 → ref
Item 2 → ref
Item 3 → ref
One approach is to store DOM elements in a ref:
const itemsRef = useRef<HTMLDivElement[]>([]);
Then callback refs can populate the array.
A simplified example:
function App() {
const itemsRef = useRef<HTMLDivElement[]>([]);
const items = ["One", "Two", "Three"];
return (
<div>
{items.map((item, index) => (
<div
key={item}
ref={(element) => {
if (element) {
itemsRef.current[index] = element;
}
}}
>
{item}
</div>
))}
</div>
);
}
You can later access:
itemsRef.current[1]
This can be useful for:
- Tabs
- Lists
- Carousels
- Navigation
- Focus management
39. useRef with animations
You can access an element and use browser APIs:
const boxRef = useRef<HTMLDivElement>(null);
const animate = () => {
boxRef.current?.animate(
[
{ transform: "translateX(0)" },
{ transform: "translateX(200px)" }
],
{
duration: 500
}
);
};
React manages the component.
The browser animation API manages the animation.
useRef connects the two.
40. useRef with WebSocket
A WebSocket connection is a good example of a value that usually shouldn't be React state.
const socketRef = useRef<WebSocket | null>(null);
Then:
socketRef.current = new WebSocket("wss://example.com");
Later:
socketRef.current?.send("Hello");
And during cleanup:
socketRef.current?.close();
Why not state?
Because the WebSocket object itself isn't UI state.
You need a persistent reference to the connection.
41. useRef with an API request controller
You can store an AbortController.
const controllerRef = useRef<AbortController | null>(null);
Before starting another request:
controllerRef.current?.abort();
controllerRef.current = new AbortController();
Then:
fetch(url, {
signal: controllerRef.current.signal
});
This is useful when you need to cancel previous requests, such as search/autocomplete.
42. useRef with React Router
You can combine refs with React Router when you need to scroll to a specific section after navigation.
For example:
const sectionRef = useRef<HTMLDivElement>(null);
Then:
sectionRef.current?.scrollIntoView();
The router controls navigation.
The ref controls access to the target DOM element.
43. useRef and React Context
A ref can be stored inside Context, but this is an advanced design.
For example, a context could expose:
focusSearchBox()
Internally, that function could use:
searchRef.current?.focus();
This can be useful for application-level commands such as:
Keyboard shortcut
|
v
Context/API
|
v
Search component
|
v
inputRef.current.focus()
However, don't use refs as a replacement for normal Context state.
44. useRef vs ordinary variable
This is an important distinction.
Consider:
let count = 0;
inside a component.
Every render executes the component function again.
Therefore:
Render 1
count = 0
Render 2
count = 0
Render 3
count = 0
The ordinary variable does not persist the way you expect.
But:
const countRef = useRef(0);
persists:
Render 1
countRef.current = 0
Change to 5
Render 2
countRef.current = 5
Render 3
countRef.current = 5
Comparison
| Normal variable | useRef |
|
|---|---|---|
| Survives render | No | Yes |
| Mutable | Yes | Yes |
| Causes render | No | No |
| Good for persistent value | No | Yes |
45. useRef vs useMemo
These hooks are very different.
useRef
Stores a mutable value.
const ref = useRef(value);
ref.current = newValue;
useMemo
Caches a calculated value.
const result = useMemo(
() => expensiveCalculation(data),
[data]
);
Think:
useRef
|
+-- "Remember this value."
useMemo
|
+-- "Cache this calculation."
Don't use useMemo when you simply need mutable persistent storage.
46. useRef vs useCallback
useCallback memoizes a function reference.
const handleClick = useCallback(() => {
...
}, []);
useRef stores a mutable value/reference.
const ref = useRef(null);
Think:
useRef
→ persistent mutable value
useCallback
→ stable function reference
47. useRef vs state
This is the most important comparison.
Suppose you have:
Shopping cart item count
Use state:
const [count, setCount] = useState(0);
because the UI must display the count.
But:
setTimeout ID
can be stored in a ref:
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
because the timer ID doesn't need to appear in the UI.
Decision rule
Ask:
Does changing this value require the UI to update?
If yes:
useState
If no:
useRef
This isn't an absolute rule, but it's an excellent starting point.
48. Important behavior: ref.current is mutable
You can do:
ref.current = 10;
Unlike state:
setValue(10);
There is no setter function.
You directly mutate:
ref.current
This is why refs are called mutable references.
49. Don't use refs to force UI updates
Avoid code like:
countRef.current++;
when the screen needs to show the new count.
Use:
setCount(prev => prev + 1);
Refs are not an alternative state-management system.
50. Don't read/write DOM refs during render unnecessarily
Avoid patterns such as:
function App() {
const inputRef = useRef<HTMLInputElement>(null);
console.log(inputRef.current);
return <input ref={inputRef} />;
}
During rendering, the DOM ref may not yet be attached.
Instead, perform DOM operations in:
- Event handlers
useEffectuseLayoutEffectwhen timing before browser paint is specifically required
For example:
useEffect(() => {
inputRef.current?.focus();
}, []);
51. useEffect vs useLayoutEffect with refs
Most DOM-related effects should use:
useEffect()
But sometimes you need to measure or synchronously modify layout before the browser paints.
Then:
useLayoutEffect()
may be appropriate.
Example:
useLayoutEffect(() => {
const width = elementRef.current?.getBoundingClientRect().width;
console.log(width);
}, []);
General rule
Normal DOM side effect
↓
useEffect
Need layout measurement/synchronous DOM work
↓
useLayoutEffect
Don't automatically use useLayoutEffect; it can block painting.
52. Important: don't store everything in refs
This is a common beginner mistake.
Bad thinking:
"I need to remember this value, so I'll use useRef."
Instead ask:
Does the UI depend on this value?
|
Yes
|
v
useState
No
|
v
Could useRef be appropriate?
For example:
const [username, setUsername] = useState("");
is usually better than:
const usernameRef = useRef("");
if the UI depends on the username.
53. TypeScript — DOM element refs
For an input:
const inputRef = useRef<HTMLInputElement>(null);
For a button:
const buttonRef = useRef<HTMLButtonElement>(null);
For a div:
const divRef = useRef<HTMLDivElement>(null);
For a video:
const videoRef = useRef<HTMLVideoElement>(null);
For a canvas:
const canvasRef = useRef<HTMLCanvasElement>(null);
The type tells TypeScript what current will contain.
54. Why initialize DOM refs with null?
This is standard:
const inputRef = useRef<HTMLInputElement>(null);
because initially:
Component hasn't mounted
|
v
DOM element doesn't exist yet
|
v
ref.current = null
After React attaches the ref:
ref.current
|
v
HTMLInputElement
Therefore you commonly use:
inputRef.current?.focus();
The ?. handles the possibility that current is null.
55. TypeScript — timer ref
For a timer:
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
For an interval:
const intervalRef =
useRef<ReturnType<typeof setInterval> | null>(null);
This works cleanly across common TypeScript environments.
56. TypeScript — custom object stored in ref
You can store your own type:
type User = {
id: number;
name: string;
};
const userRef = useRef<User | null>(null);
Then:
userRef.current = {
id: 1,
name: "Syed"
};
Access:
console.log(userRef.current?.name);
57. TypeScript — storing an object
For example:
type AppConfig = {
apiUrl: string;
timeout: number;
};
const configRef = useRef<AppConfig>({
apiUrl: "/api",
timeout: 5000
});
Then:
configRef.current.timeout = 10000;
Again, changing the ref does not cause a render.
58. Important difference: object identity
useRef returns the same ref object across renders.
Conceptually:
Render 1
|
+-- ref object A
|
+-- current = 10
Render 2
|
+-- SAME ref object A
|
+-- current = 10
This stable identity is one of the reasons refs are useful.
59. useRef does not mean "DOM ref only"
This is an important misconception.
Some beginners think:
useRefis only for accessing HTML elements.
That's not true.
You can use it for:
DOM elements
Timer IDs
Previous values
Mutable objects
WebSocket connections
Third-party library instances
AbortController
Latest values
Internal flags
External resources
The core concept is:
A persistent mutable container whose changes don't trigger rendering.
60. Real-world example: Search box
Suppose you have:
const searchRef = useRef<HTMLInputElement>(null);
You can focus the search box when the user presses a button:
const focusSearch = () => {
searchRef.current?.focus();
};
This is useful in:
Search page
|
+-- Search input
|
+-- Search button
|
+-- Keyboard shortcut
61. Real-world example: Modal focus
Suppose a modal opens.
const modalInputRef = useRef<HTMLInputElement>(null);
When the modal opens:
useEffect(() => {
if (isOpen) {
modalInputRef.current?.focus();
}
}, [isOpen]);
Flow:
isOpen = true
|
v
Modal renders
|
v
Input becomes available
|
v
useEffect()
|
v
inputRef.current.focus()
This improves keyboard accessibility.
62. Real-world example: Video player
Refs are ideal for imperative video APIs:
Play
Pause
Seek
Mute
Unmute
Set volume
Example:
videoRef.current?.play();
videoRef.current?.pause();
The video element is an external browser-managed object, so a ref is a natural bridge.
63. Real-world example: Chat application
Refs can be used for:
Latest message scrolling
Input focus
WebSocket connection
Typing timer
Message container
A typical architecture could look like:
Chat Component
|
+-- useState
| |
| +-- messages
|
+-- useRef
| |
| +-- message container
| +-- input
| +-- WebSocket
| +-- timer
|
+-- useEffect
|
+-- WebSocket setup
+-- scrolling
+-- cleanup
This is a realistic combination of React concepts.
64. Real-world example: Debounced search
A typical search component may use:
useState
|
+-- search text
useRef
|
+-- timer ID
useEffect
|
+-- API call / cleanup
This separates responsibilities nicely.
65. Real-world example: Third-party chart
Suppose a chart library expects:
new Chart(domElement)
React can provide the DOM element:
const chartRef = useRef<HTMLCanvasElement>(null);
Then:
useEffect(() => {
if (!chartRef.current) return;
const chart = new Chart(chartRef.current, options);
return () => {
chart.destroy();
};
}, []);
Here:
React
|
+-- creates canvas
|
v
useRef
|
v
chartRef.current
|
v
Chart.js / library
This is a very common integration pattern.
66. useRef and cleanup
If a ref stores an external resource, you often need cleanup.
For example:
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
timerRef.current = setInterval(() => {
console.log("Running");
}, 1000);
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, []);
The important principle is:
If you create an external resource, make sure it is cleaned up when appropriate.
Examples:
setInterval → clearInterval
setTimeout → clearTimeout
WebSocket → close
EventListener → removeEventListener
Third-party library → destroy/dispose
67. Common mistake: expecting re-render
Wrong expectation:
ref.current = 100;
and expecting:
<p>{ref.current}</p>
to automatically update.
It won't.
If UI must change:
setValue(100);
Use state.
68. Common mistake: replacing state with refs
Don't do this:
const countRef = useRef(0);
const increase = () => {
countRef.current++;
};
if the UI needs to display the count.
Use:
const [count, setCount] = useState(0);
instead.
69. Common mistake: unnecessary DOM manipulation
Avoid:
document.getElementById("name")
when React can use:
const nameRef = useRef<HTMLInputElement>(null);
and:
<input ref={nameRef} />
React refs are generally safer and more component-oriented.
However, this does not mean you should replace every DOM operation with refs. Use refs when imperative DOM access is actually needed.
70. Common mistake: modifying ref.current during render
Avoid unnecessary mutations like:
function App() {
const ref = useRef(0);
ref.current++;
return <div>...</div>;
}
This makes rendering logic harder to reason about and can behave unexpectedly under React's development rendering behavior.
Prefer changing refs in:
- Event handlers
- Effects
- Callbacks
- Other appropriate imperative code
71. Common mistake: using a ref when state is required
Ask:
Does the user need to see this value change?
If yes, state is generally the right tool.
Example:
const [isOpen, setIsOpen] = useState(false);
Not:
const isOpenRef = useRef(false);
if the UI needs to conditionally render:
{isOpen && <Modal />}
72. Common mistake: forgetting null
This can be unsafe:
inputRef.current.focus();
because current can be null.
Prefer:
inputRef.current?.focus();
or:
if (inputRef.current) {
inputRef.current.focus();
}
73. Common mistake: assuming refs are reactive
This is extremely important.
State is reactive:
state changes
↓
React renders
↓
UI changes
Ref is not reactive:
ref.current changes
↓
React does nothing automatically
Therefore:
A ref is a persistent storage mechanism, not a reactive state mechanism.
74. When should you use useRef?
Use useRef when you need:
DOM access
focus
scroll
measure
play/pause
click
selection
Persistent mutable values
timer ID
WebSocket
AbortController
third-party instance
previous value
latest value
Integration with external systems
Browser APIs
Third-party libraries
Canvas
Video
Charts
Editors
Maps
75. When should you NOT use useRef?
Don't use it when:
UI needs to react to the value
Use:
useState
You need derived data
Usually calculate it from props/state, or use appropriate memoization if expensive.
You want global state
Consider:
Context
Redux
Zustand
other state-management solutions
depending on the application.
You are trying to avoid understanding React state
Refs should not become a workaround for React's rendering model.
76. A simple decision tree
When you need to store something:
Do I need to display the value?
|
YES
|
v
useState
NO
|
v
Does it need to survive renders?
|
YES
|
v
useRef
NO
|
v
Can it be a normal local variable?
For DOM access:
Need access to DOM element?
|
YES
|
v
useRef
77. useRef mental model
A very useful way to remember useRef is:
useRefis like a small persistent box attached to your component.
Component
|
+----------------+
| |
| ref |
| |
| current: 123 |
| |
+----------------+
The box survives renders.
You can change what's inside:
ref.current = 456;
But React doesn't re-render just because the box changed.
78. Complete comparison of common React hooks
| Hook | Main purpose |
|---|---|
useState |
Store reactive UI state |
useRef |
Store persistent mutable value / DOM reference |
useEffect |
Synchronize with external systems |
useLayoutEffect |
Perform layout-sensitive effects |
useMemo |
Cache expensive calculated value |
useCallback |
Cache function reference |
useContext |
Read shared context |
useReducer |
Manage complex state transitions |
A useful distinction:
useState
→ "The UI needs to know."
useRef
→ "I need to remember this."
useEffect
→ "I need to synchronize with something outside React."
79. Interview-focused questions
What is useRef?
useRef is a React Hook that creates a persistent mutable reference object. Its current value survives re-renders, and changing it does not trigger a re-render.
Does changing ref.current cause re-render?
No.
ref.current = 100;
does not cause React to render again.
What are the two major uses of useRef?
- Accessing DOM elements.
- Storing mutable values that must persist between renders without causing rendering.
Does useRef preserve values between renders?
Yes.
The ref object remains stable across renders.
useRef vs useState?
useState is for reactive UI state and causes re-rendering when updated. useRef is for persistent mutable values or DOM references and does not cause re-rendering.
Can useRef store objects?
Yes.
const ref = useRef<MyObject | null>(null);
Can useRef access DOM elements?
Yes.
const inputRef = useRef<HTMLInputElement>(null);
Why is null commonly used with DOM refs?
Because the DOM element does not exist before the component mounts.
Can useRef replace useState?
No. It can replace state only in situations where changing the value should not trigger a UI update.
Can useRef store a timer ID?
Yes. This is a common pattern.
Can useRef be used with useEffect?
Yes. They are frequently used together for DOM manipulation, timers, subscriptions, external resources, and third-party libraries.
80. The most important rules to remember
Rule 1
useRef()
returns an object:
{
current: ...
}
Rule 2
Access the value using:
ref.current
Rule 3
The value survives renders.
Rule 4
Changing:
ref.current
doesn't cause a render.
Rule 5
Use refs for DOM access.
Rule 6
Use state when the UI needs to react to a value change.
Rule 7
Don't use refs as a replacement for normal React state.
Rule 8
For DOM refs in TypeScript, commonly initialize with null:
useRef<HTMLInputElement>(null)
Rule 9
Use effects when DOM/external-system work needs to happen as part of synchronization with rendering.
Rule 10
Clean up timers, subscriptions, connections, and third-party resources.
81. Final practical example
Consider a small search component:
import { useEffect, useRef, useState } from "react";
function SearchBox() {
const [search, setSearch] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const timerRef =
useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
}, []);
const handleSearch = (value: string) => {
setSearch(value);
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
console.log("Searching for:", value);
}, 500);
};
const focusInput = () => {
inputRef.current?.focus();
};
return (
<div>
<input
ref={inputRef}
value={search}
onChange={e => handleSearch(e.target.value)}
placeholder="Search..."
/>
<button onClick={focusInput}>
Focus
</button>
</div>
);
}
This example demonstrates several concepts together:
useState
|
+-- search text
+-- UI updates when search changes
useRef
|
+-- input DOM element
+-- timer ID
useEffect
|
+-- cleanup timer
This is the kind of combination you will frequently see in real React applications.
82. Summary
The simplest way to understand useRef is:
useRef
|
+-- Persistent value
|
+-- Mutable
|
+-- Survives renders
|
+-- Does NOT cause re-render
|
+-- Can reference DOM elements
Remember this comparison
useState
↓
Value changes
↓
React re-renders
↓
UI updates
useRef
↓
ref.current changes
↓
React does NOT re-render
↓
Value remains available
Most common real-world uses
1. Focus an input
2. Scroll to an element
3. Access video/audio
4. Trigger a file input
5. Store previous values
6. Store timer/interval IDs
7. Debouncing
8. Store WebSocket connections
9. Integrate third-party libraries
10. Work with Canvas
11. Manage DOM measurements
12. Expose imperative component APIs
The key interview sentence to remember is:
useRefprovides a persistent mutable reference whose.currentvalue survives re-renders without causing a re-render when changed. It is commonly used for DOM access and for storing mutable values that don't belong in React state.
The two main purposes of useRef are:
- Access a DOM element — not just
<input> - Store a value that persists between renders without causing a re-render
1. Access any DOM element
You can use useRef with almost any HTML element.
const buttonRef = useRef<HTMLButtonElement>(null);
<button ref={buttonRef}>Click</button>
Then:
buttonRef.current?.click();
Other examples:
const divRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const sectionRef = useRef<HTMLElement>(null);
For example, control a video:
const videoRef = useRef<HTMLVideoElement>(null);
const playVideo = () => {
videoRef.current?.play();
};
const pauseVideo = () => {
videoRef.current?.pause();
};
return (
<>
<video ref={videoRef} src="/video.mp4" />
<button onClick={playVideo}>Play</button>
<button onClick={pauseVideo}>Pause</button>
</>
);
Here useRef is not remembering a value. It is giving you access to the actual <video> DOM element.
2. Store a value without re-rendering
This is the other major use.
const countRef = useRef(0);
const increment = () => {
countRef.current++;
console.log(countRef.current);
};
Every time you call increment():
countRef.current
↓
1
2
3
4
5
The value is remembered.
But React does not re-render the component.
This is useful for things like:
- Timer IDs
- Previous values
- WebSocket objects
- DOM references
- Third-party library instances
- Debounce/throttle timers
- Previous render information
- Flags that don't need to appear in the UI
Very important distinction
Think of useRef as a persistent box.
const myRef = useRef(value);
You get:
myRef
|
└── current
|
└── your value
You can put almost anything inside:
myRef.current = 10;
myRef.current = "Hello";
myRef.current = { name: "Syed" };
myRef.current = someObject;
myRef.current = timerId;
So useRef is not an "input hook".
A better definition is:
useRefgives you a persistent mutable value that survives re-renders without causing a re-render when changed. It can also hold a reference to a DOM element.
Simple rule to remember
| Requirement | Use |
|---|---|
| Value should update the UI | useState |
| Value should survive re-render but shouldn't update UI | useRef |
| Need direct access to a DOM element | useRef |
So if you're asking "Apart from avoiding re-render, what is the real purpose?" — the most important answer is imperative access to things React normally manages declaratively, especially DOM elements and external objects.