Introduction
The useRef Hook allows a React component to keep a value between renders without causing a re-render when that value changes. It is also commonly used to access DOM elements directly, such as focusing an input or controlling a video element. In this chapter, we will solve practical useRef questions covering DOM references, persistent values, and common React use cases. React js useRef Hook practice questions with solutions help to understand the concepts.
1. What is the useRef Hook in React?
useRef is a React Hook that lets you create a mutable reference object whose value remains available between renders.
Basic syntax:
import { useRef } from "react";
function App() {
const myRef = useRef();
return <h1>Hello React</h1>;
}
export default App;
A ref object contains a current property:
const myRef = useRef();
console.log(myRef.current);
You can update myRef.current without causing the component to re-render.
2. Why is useRef used in React?
useRef is commonly used for two main purposes:
- Accessing DOM elements.
- Storing a value that should persist between renders without triggering a re-render.
For example, you can use a ref to focus an input:
const inputRef = useRef();
inputRef.current.focus();
Refs are useful when you need to interact with something outside React’s normal rendering flow.
3. How do you create a Ref using useRef?
Import useRef from React and call it inside a component.
import { useRef } from "react";
function App() {
const countRef = useRef(0);
return <h1>React useRef</h1>;
}
export default App;
Here:
countRef.current
contains the current value of the ref.
You can update it like this:
countRef.current = 10;
Changing current does not automatically cause a re-render.
4. How do you use useRef to access an input element?
You can connect a ref to an input using the ref attribute.
import { useRef } from "react";
function App() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={() => inputRef.current.focus()}>
Focus Input
</button>
</div>
);
}
export default App;
When React commits the DOM element, inputRef.current points to the input element.
Clicking the button calls:
inputRef.current.focus();
This focuses the input.
5. Does changing a useRef value cause a re-render?
No.
Updating ref.current does not trigger a React re-render.
Example:
import { useRef } from "react";
function App() {
const countRef = useRef(0);
const increase = () => {
countRef.current += 1;
console.log(countRef.current);
};
return (
<button onClick={increase}>
Increase
</button>
);
}
export default App;
The value of countRef.current changes, but React does not automatically update the screen because of that change.
If the value needs to appear in the UI and update visually, useState is usually the appropriate choice.
6. How do you use useRef to store a value between renders?
A ref can store a value that should remain available across renders.
import { useRef, useState } from "react";
function App() {
const valueRef = useRef(0);
const [count, setCount] = useState(0);
const updateValue = () => {
valueRef.current += 1;
console.log("Ref value:", valueRef.current);
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Re-render
</button>
<button onClick={updateValue}>
Update Ref
</button>
</div>
);
}
export default App;
The value stored in valueRef.current remains available when the component renders again.
This makes refs useful for values that do not directly control the UI.
7. What is the difference between useRef and useState?
Both can store values, but they behave differently.
useState | useRef |
|---|---|
| Stores state for rendering | Stores a mutable reference |
| Updating state schedules a re-render | Updating ref.current does not trigger a re-render |
| Used for values displayed in UI | Often used for DOM references or non-visual values |
| State updates should use React’s state update mechanism | ref.current can be directly changed |
Example with state:
const [count, setCount] = useState(0);
setCount(count + 1);
Example with ref:
const countRef = useRef(0);
countRef.current += 1;
Choose useState when changing the value should update the UI. Use useRef when the value needs to persist but does not need to trigger a render.
8. How do you use useRef to store the previous value?
A ref can be used to remember a value from a previous render.
import { useEffect, useRef, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const previousCount = useRef();
useEffect(() => {
previousCount.current = count;
}, [count]);
return (
<div>
<h2>Current: {count}</h2>
<h3>
Previous: {previousCount.current ?? "No previous value"}
</h3>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
The ref is updated after the effect runs, so it can retain the value from the previous completed render for the next render.
9. Can useRef be used with DOM elements other than inputs?
Yes.
Refs can be used with DOM elements such as:
<input><textarea><button><div><video><audio>
For example, controlling a video element:
import { useRef } from "react";
function VideoPlayer() {
const videoRef = useRef(null);
const playVideo = () => {
videoRef.current.play();
};
return (
<div>
<video
ref={videoRef}
width="400"
controls
>
<source src="/video.mp4" type="video/mp4" />
</video>
<button onClick={playVideo}>
Play Video
</button>
</div>
);
}
export default VideoPlayer;
Here, videoRef.current refers to the video DOM element after it has been attached.
10. Build a Practical Auto-Focus Input using useRef
Create a form where the input automatically receives focus when the component is mounted.
Solution:
import { useEffect, useRef } from "react";
function LoginForm() {
const usernameRef = useRef(null);
useEffect(() => {
usernameRef.current.focus();
}, []);
return (
<div>
<h1>Login</h1>
<input
ref={usernameRef}
type="text"
placeholder="Enter username"
/>
<button>Login</button>
</div>
);
}
export default LoginForm;
How it works:
useRef(null)creates a ref.- The ref is attached to the input using
ref={usernameRef}. - After the input is mounted,
usernameRef.currentrefers to that DOM element. - The effect calls
.focus()on the input. - The user can start typing without manually clicking the input.
This is a simple and practical use case for useRef.
Key Takeaways
useRefis a React Hook for keeping a mutable value between renders.- A ref object contains a
currentproperty. - Updating
ref.currentdoes not trigger a re-render. useRefis commonly used to access DOM elements.- Refs can be attached using the
refattribute. useRefcan store values that need to persist between renders.- Refs can be useful for remembering previous values.
useRefis different fromuseStatebecause changing a ref does not update the UI automatically.- DOM methods such as
focus()can be accessed through a DOM ref. - Refs should be used when direct DOM interaction or persistent non-rendering values are actually needed.
FAQs
1. What is useRef in React?
useRef is a React Hook that creates a mutable reference object that can persist between renders.
2. What is ref.current in React?
ref.current stores the current value of a ref. For a DOM ref, it can point to the associated DOM element after React attaches it.
3. Does changing useRef cause a re-render?
No. Changing ref.current does not automatically trigger a React re-render.
4. What is the difference between useRef and useState?
useState updates can cause a component to re-render, while changing ref.current does not trigger a re-render.
5. Can useRef access DOM elements?
Yes. You can attach a ref to a DOM element and use ref.current to access that element after it has been attached.
6. Can useRef store previous values?
Yes. A ref can be used to retain a value between renders, including a value from a previous render when updated at the appropriate time.
7. When should I use useRef instead of useState?
Use useRef when a value needs to persist between renders but changing it should not cause the component to re-render. Use useState when the value affects what should be displayed in the UI.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
