useRef Hook in React JS – Complete Detailed Notes
The useRef Hook is a built-in React Hook that allows developers to store values between renders without causing a component to re-render when the value changes. It is commonly used to access DOM elements, focus input fields, store timer IDs, manage previous values, and interact with browser APIs.
Learn more through JustAcademy React JS Training or Register for React JS Course Demo.
1. What Is the useRef Hook?
In React, components render their UI using props and state. Sometimes, a component needs to remember a value that does not directly affect the UI, or it needs to access a DOM element created by React. The useRef Hook is designed for these situations.
The useRef Hook returns a JavaScript object containing a property named current. You can read or update this property to retain information between renders.
Basic syntax
import { useRef } from 'react';
const myRef = useRef(initialValue);
Here, initialValue is the value assigned to myRef.current during the initial render. React returns the same ref object on subsequent renders of that component instance.
Example
import { useRef } from 'react';
function Example() {
const countRef = useRef(0);
function handleClick() {
countRef.current = countRef.current + 1;
alert(`Count: ${countRef.current}`);
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default Example;
Explanation: The initial value of countRef.current is zero. Each click increases the stored value. Updating the ref does not automatically re-render the component.
2. Why Do We Use useRef?
The useRef Hook is useful when a component needs to retain information without using that information to calculate its rendered output.
- Accessing DOM elements: Focus an input, scroll to an element, or measure its size.
- Storing mutable values: Retain a value between renders without triggering a new render.
- Managing timers: Store interval or timeout IDs so they can be cleared later.
- Remembering previous values: Keep a previous value for comparison in an Effect or event handler.
- Integrating browser APIs: Store references to media elements, animation objects, or other external resources.
Use state instead when changing a value should immediately update what the user sees on the screen.
3. Understanding the current Property
Every ref object returned by useRef contains a current property. Initially, this property holds the value supplied to useRef. It can later be updated.
import { useRef } from 'react';
function Example() {
const messageRef = useRef('Hello');
function updateMessage() {
messageRef.current = 'Welcome to React';
alert(messageRef.current);
}
return (
<button onClick={updateMessage}>
Show Message
</button>
);
}
export default Example;
Important points
messageRef is the ref object.
messageRef.current stores the current value.
- The value can be changed without calling a state setter.
- Changing the value does not trigger a render.
- If a ref is attached to a DOM element, React assigns that DOM node to
current after the element is committed and sets it back to null when the element is removed.
4. Accessing DOM Elements With useRef
One of the most common uses of useRef is accessing a DOM element directly. React usually manages the DOM automatically, but some operations, such as focusing an input or scrolling to an element, require direct access.
Example: Focus an Input Field
import { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current?.focus();
}
return (
<div>
<h2>Focus Input Example</h2>
<input
ref={inputRef}
type="text"
placeholder="Enter your name"
/>
<button onClick={handleFocus}>
Focus Input
</button>
</div>
);
}
export default FocusInput;
How it works
useRef(null) creates a ref with an initial value of null.
- The ref is attached to the input using
ref={inputRef}.
- React assigns the input DOM element to
inputRef.current.
- When the button is clicked, the handler calls the input's
focus() method.
- The cursor moves into the input field.
The optional chaining operator ?. prevents an error if the ref does not currently point to an element.
5. useRef vs useState
Both useRef and useState retain information between renders, but they behave differently.
| Feature |
useRef |
useState |
| Purpose |
Stores values not needed to calculate rendered output. |
Stores values that affect the rendered UI. |
| Return value |
An object with a current property. |
An array containing the current state and a setter function. |
| Updating values |
Assign a new value to ref.current. |
Call the state setter function. |
| Triggers re-render |
No, changing the ref does not trigger a render. |
Normally, updating state schedules a render when the state changes. |
| Mutability |
The current property is mutable. |
State should be updated through its setter, not mutated directly. |
| Common use |
DOM nodes, timer IDs, external objects. |
Form values, counters, toggles, lists and displayed data. |
Example: useState updates the UI
import { useState } from 'react';
function StateCounter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default StateCounter;
Here, React re-renders the component after the count state changes, so the displayed number is updated.
Example: useRef stores a value without updating the UI
import { useRef } from 'react';
function RefCounter() {
const countRef = useRef(0);
function increaseCount() {
countRef.current += 1;
alert(`Stored count: ${countRef.current}`);
}
return (
<button onClick={increaseCount}>
Increase Stored Count
</button>
);
}
export default RefCounter;
The stored count changes when the button is clicked, but the component does not re-render because of the ref update. Therefore, useRef is not suitable for displaying a changing count directly.
6. Storing Timer IDs With useRef
When working with timers, you may need to save an interval ID so that you can stop the timer later. A ref is useful because the timer ID does not normally need to be displayed on the screen.
Example: Start and Stop a Timer
import { useRef, useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
function startTimer() {
if (intervalRef.current !== null) return;
intervalRef.current = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
}
function stopTimer() {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
function resetTimer() {
stopTimer();
setSeconds(0);
}
useEffect(() => {
return () => {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
}
};
}, []);
return (
<div>
<h2>Timer: {seconds} seconds</h2>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
);
}
export default Timer;
Explanation
intervalRef stores the interval ID.
startTimer() starts the timer only if one is not already running.
setSeconds() updates the visible timer value using state.
stopTimer() clears the interval and resets the ref to null.
resetTimer() stops the timer and resets the displayed count.
- The cleanup function clears any remaining interval when the component is removed.
This example demonstrates why refs and state often work together: useRef manages the timer resource, while useState updates the UI.
7. Tracking Previous Values With useRef
A ref can retain a value from a previous render. A common approach is to update the ref in an Effect after React commits the current render.
Example: Track Previous Count
import { useEffect, useRef, useState } from 'react';
function PreviousCount() {
const [count, setCount] = useState(0);
const previousCountRef = useRef();
useEffect(() => {
previousCountRef.current = count;
}, [count]);
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {previousCountRef.current ?? 'None'}</p>
<button onClick={() => setCount(value => value + 1)}>
Increase
</button>
</div>
);
}
export default PreviousCount;
How it works: The Effect stores the current count in the ref after the render commits. On the next render, the ref contains the count stored by the previous Effect execution. Initially, the previous value is undefined, so the UI displays None.
Note: Do not read or write ref.current during ordinary rendering to calculate changing UI. This example reads the ref to demonstrate a previous-value pattern, but React recommends using state when a value is needed for rendering. For UI that must update reliably with the previous value, consider storing that value in state or deriving it from state transitions.
8. Using useRef With Forms
useRef can access form elements directly, such as an input field. This is useful when you need to focus an input, select text, or read an input value at a particular event. However, if the UI must react to every input change, controlled inputs using useState are often a better choice.
Example: Read an Input Value
import { useRef, useState } from 'react';
function NameForm() {
const nameRef = useRef(null);
const [submittedName, setSubmittedName] = useState('');
function handleSubmit(event) {
event.preventDefault();
setSubmittedName(nameRef.current?.value.trim() || '');
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Your Name:</label>
<input
id="name"
ref={nameRef}
type="text"
placeholder="Enter your name"
/>
<button type="submit">Submit</button>
{submittedName && (
<p>Hello, {submittedName}!</p>
)}
</form>
);
}
export default NameForm;
Explanation
- The input element is connected to
nameRef.
- When the form is submitted, the browser's default submission is prevented.
- The handler reads the input's value from
nameRef.current.value.
- The submitted name is saved in state.
- React renders a greeting using the submitted value.
9. Accessing DOM Methods With useRef
A DOM ref provides access to browser methods and properties on the referenced element. For example, you can focus an input, select text, scroll to an element, or measure an element's dimensions.
| Method or Property |
Purpose |
Example |
focus() |
Moves keyboard focus to an element. |
inputRef.current.focus() |
blur() |
Removes focus from an element. |
inputRef.current.blur() |
select() |
Selects the text in an input. |
inputRef.current.select() |
scrollIntoView() |
Scrolls an element into view. |
sectionRef.current.scrollIntoView() |
getBoundingClientRect() |
Gets an element's position and dimensions. |
elementRef.current.getBoundingClientRect() |
Example: Scroll to a Section
import { useRef } from 'react';
function ScrollExample() {
const sectionRef = useRef(null);
function scrollToSection() {
sectionRef.current?.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
return (
<div>
<button onClick={scrollToSection}>
Go to Details
</button>
<div style={{ height: '500px' }}>
Scroll down to see the details.
</div>
<section ref={sectionRef}>
<h2>Details Section</h2>
<p>You have reached the details section.</p>
</section>
</div>
);
}
export default ScrollExample;
The ref provides access to the section element, and scrollIntoView() scrolls the page to that element when the button is clicked.
10. useRef With useEffect
useRef and useEffect can be combined when a component needs to work with a DOM element or an external resource after rendering. The ref stores the reference, and the Effect performs the synchronization.
Example: Focus an Input on Initial Display
import { useEffect, useRef } from 'react';
function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return (
<div>
<h2>Automatic Focus Example</h2>
<input
ref={inputRef}
type="text"
placeholder="Start typing..."
/>
</div>
);
}
export default AutoFocusInput;
Explanation: React attaches the DOM element to the ref during the commit. The Effect then runs and focuses the input. In development Strict Mode, Effects may undergo an additional setup-and-cleanup cycle, so Effects should be designed to remain correct when repeated.
11. Common Mistakes When Using useRef
| Mistake |
Why It Is a Problem |
Correct Approach |
| Using a ref for visible data |
Changing the ref does not trigger a render, so the UI may not update. |
Use useState for values that affect the UI. |
| Accessing a DOM ref before it is attached |
The current value may still be null. |
Access it in an event handler or Effect after the DOM node has been committed. |
| Forgetting to clear a timer |
The timer may continue running after it is no longer needed. |
Clear the timer and reset its ref when appropriate. |
| Calling useRef conditionally |
Hooks must be called in a consistent order. |
Call useRef at the top level of the component or custom Hook. |
| Reading or writing ref.current during rendering |
Can make rendering unpredictable and conflict with React's expectations. |
Use refs in event handlers and Effects, except for safe initialization patterns. |
| Directly changing DOM structure unnecessarily |
Manual DOM changes may conflict with React's own DOM updates. |
Use refs for focused imperative operations and let React manage the UI. |
12. Rules of the useRef Hook
- Import useRef from React before using it.
- Call useRef at the top level of a function component or custom Hook.
- Pass an initial value, such as null, zero, or a string.
- Access the stored value through the
current property.
- Use refs for values that do not need to trigger a re-render.
- Use state for values that must be reflected in the UI.
- Do not call Hooks inside loops, conditions, or nested functions.
- Do not read or write refs during rendering except for predictable initialization.
- Check whether a DOM ref is null before calling methods on it.
- Clean up timers, subscriptions, or external resources when they are no longer needed.
13. Practical Project: Focus and Clear an Input
Build a small input utility with buttons to focus the input, select its text, and clear its contents.
import { useRef } from 'react';
function InputUtility() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current?.focus();
}
function selectText() {
inputRef.current?.select();
}
function clearInput() {
if (inputRef.current) {
inputRef.current.value = '';
inputRef.current.focus();
}
}
return (
<div>
<h2>Input Utility</h2>
<input
ref={inputRef}
type="text"
defaultValue="React JS"
placeholder="Enter text"
/>
<button onClick={focusInput}>Focus</button>
<button onClick={selectText}>Select Text</button>
<button onClick={clearInput}>Clear</button>
</div>
);
}
export default InputUtility;
Project learning outcomes
- Learn how to create and attach a DOM ref.
- Understand how to call native DOM methods.
- Practice focusing and selecting text programmatically.
- Understand the difference between direct DOM operations and React state updates.
This example uses an uncontrolled input, so changing its DOM value directly is appropriate for this simple demonstration. For a controlled input whose value is managed by React state, update the state instead of modifying the DOM value directly.
14. Interview Questions and Answers
Q1. What is useRef in React?
Answer: useRef is a React Hook that stores a mutable value between renders without triggering a re-render when that value changes.
Q2. What does useRef return?
Answer: It returns a JavaScript object with a current property.
Q3. What is the purpose of ref.current?
Answer: It stores the current value of a ref. That value can be a DOM element, timer ID, number, object, or another JavaScript value.
Q4. Does updating a ref cause a re-render?
Answer: No. Updating ref.current does not trigger a component re-render.
Q5. What is the difference between useRef and useState?
Answer: useState is used for values that affect the UI and schedules a render when the state changes. useRef stores values that can change without triggering a render.
Q6. How can useRef focus an input?
Answer: Create a ref with useRef(null), attach it to an input using the ref attribute, and call inputRef.current.focus() from an event handler or Effect.
Q7. Can useRef store a timer ID?
Answer: Yes. A ref can store the ID returned by setInterval or setTimeout so the timer can be cleared later.
Q8. Can we use useRef outside a component?
Answer: No. The useRef Hook must be called inside a function component or custom Hook at the top level.
Q9. What is the initial value of a DOM ref?
Answer: It is commonly initialized with null. React assigns the DOM node to current when the node is committed to the DOM.
Q10. Can a ref hold values other than DOM elements?
Answer: Yes. It can hold numbers, strings, objects, timer IDs, and other values.
Q11. When should useRef not be used?
Answer: Avoid using a ref for data that must update the visible UI. Use state for that data.
Q12. Can a ref value be changed directly?
Answer: Yes. You can assign a new value to ref.current. However, avoid reading or writing refs during rendering except for safe initialization.
15. Practice Exercises
- Create a component that focuses an email input when a button is clicked.
- Build a counter that stores its click count in a ref and displays the value in an alert.
- Create a stopwatch using useRef to store the interval ID and useState to display elapsed time.
- Build a form that reads an uncontrolled input using a ref when the form is submitted.
- Create a button that scrolls to a particular section using
scrollIntoView().
- Write a component that tracks a previous state value and explain when the ref is updated.
- Compare useRef and useState by creating two separate counters.
16. Quick Revision Checklist
- Understand the definition and syntax of useRef.
- Know the purpose of the
current property.
- Understand how refs retain values between renders.
- Know why updating a ref does not trigger a re-render.
- Practice attaching refs to DOM elements.
- Learn to focus, select, and scroll to elements.
- Understand how refs can store timer IDs.
- Know the difference between useRef and useState.
- Follow the Rules of Hooks and avoid unnecessary DOM manipulation.
- Clean up timers and external resources appropriately.
17. Official React Documentation
18. Conclusion
The useRef Hook is an important React feature for retaining values between renders without causing additional renders. It is especially useful for accessing DOM elements, controlling focus, storing timer IDs, and interacting with browser APIs.
Remember the main rule: useRef is for values that do not need to trigger a UI update, while useState is for values that affect the rendered interface. Practice the examples and exercises to understand how refs work in real React applications.
Explore JustAcademy React JS Training and Register for React JS Course Demo to learn more about React JS concepts and practical development.