The useRef hook allows you to persist values between renders without triggering a re-render. Whether you’re dealing with DOM manipulation, storing previous values, or managing timers, useRef is an efficient solution.
What is useRef hook?
The useRef allows to directly create a reference to the DOM element in the functional component. The useRef hook is a new addition in React 16.8. To learn useRef the user should be aware of refs in React. Unlike useState if we change a value in useRef it will not re-render the webpage.
Example:
import React, { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}Reasons to use useRef hook
The main use of useRef hook is to access the DOM elements in a more efficient way as compared to simple refs. Since useRef hooks preserve value across various re-renders and do not cause re-renders whenever a value is changed they make the application faster and helps in caching and storing previous values
Importing useRef hook
To import the useRef hook, write the following code at the top level of your component
import { useRef } from 'react';Structure of useRef hook
It accepts only one initial value
Syntax:
const refContainer = useRef(initialValue);
The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component. The useRef hook is useful for persisting values across renders without causing re-renders.
Implementing the useRef hook
Example: How to access the DOM using useRef hook.
JavaScript
import React, { Fragment, useRef } from 'react';
function App() {
// Creating a ref object using useRef hook
const focusPoint = useRef(null);
const onClickHandler = () => {
focusPoint.current.value =
"The quick brown fox jumps over the lazy dog";
focusPoint.current.focus();
};
return (
<Fragment>
<div>
<button onClick={onClickHandler}>
ACTION
</button>
</div>
<label>
Click on the action button to
focus and populate the text.
</label><br />
<textarea ref={focusPoint} />
</Fragment>
);
};
export default App;
Output: In this example, we have a button called ACTION, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with the help of useRef hook.

React JS useRef Hook
Accessing DOM Elements with useRef
One of the most common use cases of useRef is accessing DOM elements directly. This is particularly useful when you need to manipulate an element, such as focusing an input field, as shown earlier.
Here’s a more complex example of using useRef to control video playback:
function VideoPlayer() {
const videoRef = useRef(null);
const playVideo = () => {
videoRef.current.play();
};
const pauseVideo = () => {
videoRef.current.pause();
};
return (
<div>
<video ref={videoRef} width="400" controls>
<source src="video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
<button onClick={playVideo}>Play</button>
<button onClick={pauseVideo}>Pause</button>
</div>
);
}Persisting Values Across Renders
In addition to accessing DOM elements, useRef is useful for storing values that persist across renders. A common use case is storing a previous value, such as the previous state or props.
Example:
function PreviousValue() {
const [count, setCount] = React.useState(0);
const prevCountRef = useRef();
React.useEffect(() => {
prevCountRef.current = count;
}, [count]);
return (
<div>
<p>Current count: {count}</p>
<p>Previous count: {prevCountRef.current}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}useRef vs useState
While both useRef and useState allow you to store values, they serve different purposes:
- useState: Triggers a re-render when the state value changes.
- useRef: Does not cause re-renders when the value updates. It is primarily used for persisting values or accessing DOM elements.
| Feature | useRef | useState |
|---|
| Triggers re-render | No | Yes |
| Use case | Accessing DOM, persisting values | Handling component state |
| Initial value | Optional | Required |
Similar Reads
ReactJS useRef Hook
The useRef hook allows you to persist values between renders without triggering a re-render. Whether you're dealing with DOM manipulation, storing previous values, or managing timers, useRef is an efficient solution. Table of Content What is useRef hook?Reasons to use useRef hookImplementing the use
4 min read
ReactJS useEffect Hook
React useEffect hook handles the effects of the dependency array. The useEffect Hook allows us to perform side effects on the components. fetching data, directly updating the DOM and timers are some side effects. It is called every time any state if the dependency array is modified or updated. In th
5 min read
ReactJS useReducer Hook
The useReducer Hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components are needed to be optimized. The useReducer hook tak
2 min read
ReactJS useId Hook
React useId Hook is introduced for the ReactJS versions above 18. This hook generates unique IDs i.e, returns a string that is stable across both the server and the client sides. Prerequisite: Introduction and installation of ReactJSReact Hooks Syntax: const id = useId() Creating React Application:
3 min read
ReactJS useSelect hook
The useSelect is a custom hook provided by the Rooks package for React. It is a list selection hook that helps select values from a list. Arguments: list: It is of the type array which describes the list of items for the selection. The default value is undefined.initialIndex -It is of the type numbe
2 min read
ReactJS useParams Hook
React JS useParams Hook helps to access the parameters of the current route to manage the dynamic routes in the URL. The react-router-dom package has useParams hooks that let you access and use the parameters of the current route as required. Prerequisites:NPM & Node.jsReact JSreact-router-domAp
2 min read
ReactJS useContext Hook
Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme(e.g. co
2 min read
React useState Hook
useState Hook is used to access state in the React functional components. It is a special function that allows you to manage state within functional components without the need for class-based components. The useState hook is a powerful addition to React, introduced in version 16.8. In this useState
6 min read
ReactJS useNavigate() Hook
The useNavigate() hook is introduced in the React Router v6 to replace the useHistory() hook. In the earlier version, the useHistory() hook accesses the React Router history object and navigates to the other routers using the push or replace methods. It helps to go to the specific URL, and forward o
4 min read
ReactJS useLayoutEffect Hook
The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
2 min read
ReactJS useUndoState hook
The useUndoState hook is a custom hook provided by the Rooks package for React. It is similar to the useState hook in addition to undo functionality. Arguments: initialValue: It is of the type boolean that describes the initial value of the state. Its default value is false.Options: It is of the typ
2 min read
Ref Hooks in React
Ref Hooks provide a way to access and interact with the DOM (Document Object Model) nodes directly within functional components. Before hooks, refs were primarily used in class components. However, with Ref Hooks, functional components can also take advantage of this capability, enhancing flexibilit
4 min read
ReactJs useDebugValue Hook
React useDebugValue Hook is introduced for the ReactJs versions above 18. React useDebugValue Hook helps developers debug custom hooks in React Developer Tools by adding additional information and labels to those hooks. Prerequisite:ReactJSReact Developer ToolsReact HooksReact Custom HooksApproach:T
2 min read
React-Router Hooks
React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single pa
12 min read
ReactJS Refs
ReactJS Refs are used to access and modify the DOM elements in the React Application. It creates a reference to the elements and uses it to modify them. Table of Content Creating refs in ReactAccessing Refs in ReactWhy useRef over createRef in Function Components?When to use refsWhen not to use refs
5 min read
How useRef Hook is useful in React ?
Hooks provides a way to useState and other React features in functional components without the need for class components. We can either use built-in hooks or customize and make our own. One of those hooks in useRef. It allows reference to a value that does not require rendering. It can be used to st
5 min read
React useCallback Hook
React useCallback hook returns a memoized function to reduce unnecessary callbacks. This useCallback hook is used when you have a component in which the child is rerendering again and again without need. Table of Content React useCallback HookReact useCallback Hook UsageWithout using the useCallback
4 min read
State Hooks in React
State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
3 min read
Resource Hooks in React
In React, components often need to access external resources such as data from promises or context information for styling. Managing these resources within the component state could lead to unnecessary complexity and performance overhead. React provides a simple solution with the 'use' hook to overc
3 min read