React useRef Hook
25 April 2025 | Category: React Js
React’s useRef
Hook is like a secret drawer—you can put things inside and they’ll stay there, even after re-renders.
Let’s break it down step-by-step with simple language and real-world examples. 👇
🧠 What is useRef
?
useRef
is a built-in React Hook that lets you:
- Reference DOM elements (like focusing an input)
- Persist values across renders without causing re-renders
- Store mutable values without triggering component updates
🧪 Syntax
const ref = useRef(initialValue);
ref.current
will hold the value you can update or read.
📦 Importing useRef
import { useRef } from 'react';
📌 Use Case 1: Accessing DOM Elements
Let’s create a simple input field and focus on it with a button click.
✅ Example: Auto-Focus an Input
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus(); // Access DOM node directly
};
return (
<div>
<input ref={inputRef} placeholder="Type here..." />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
export default FocusInput;
🧠 Explanation:
inputRef
stores a reference to the input DOM element.- When the button is clicked, it calls
inputRef.current.focus()
.
📌 Use Case 2: Persisting Values Between Renders
Sometimes you want to store a value without causing a re-render—like keeping track of how many times a button was clicked.
✅ Example: Count Renders Without Re-rendering
import React, { useRef, useState, useEffect } from 'react';
function RenderCounter() {
const [count, setCount] = useState(0);
const renderCount = useRef(1);
useEffect(() => {
renderCount.current += 1;
});
return (
<div>
<p>Button clicked: {count} times</p>
<p>Component rendered: {renderCount.current} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
💡 Why not use useState
?
Because useState
will re-render the component every time it’s updated. useRef
will not trigger re-renders.
📌 Use Case 3: Storing Previous Values
You can also use useRef
to track the previous state of a variable.
✅ Example: Show Previous Count
import React, { useState, useEffect, useRef } from 'react';
function PreviousCount() {
const [count, setCount] = useState(0);
const prevCount = useRef();
useEffect(() => {
prevCount.current = count;
}, [count]);
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCount.current}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
📋 Summary of useRef Features
Feature | useRef |
---|---|
References DOM elements | ✅ Yes |
Persists value across renders | ✅ Yes |
Triggers re-render when updated | ❌ No |
Stores mutable values | ✅ Yes |
Tracks previous values | ✅ Yes (with useEffect) |
🛑 Common Mistakes to Avoid
- ❌ Trying to update UI directly using
ref.current
values. Remember: changingref.current
won’t cause a re-render. - ❌ Confusing
useRef
withuseState
. UseuseRef
for non-UI state or DOM manipulation, not for values that must update the UI.
🧠 When to Use useRef
- To directly interact with the DOM (like focusing, scrolling, or measuring elements)
- To store values that don’t affect rendering (like timers, intervals, or previous state)
- To avoid unnecessary re-renders for certain operations
🔁 useRef vs useState
Feature | useRef | useState |
---|---|---|
Causes re-render | ❌ No | ✅ Yes |
Persistent across renders | ✅ Yes | ✅ Yes |
Use for DOM reference | ✅ Yes | ❌ No |
Best for UI display | ❌ No | ✅ Yes |
🎯 Mini Project Ideas to Practice useRef
- Focus trap for login modal
- Countdown timer with pause/resume
- Previous scroll position tracker
- Custom stop-watch with Start/Pause/Reset