close
The Wayback Machine - https://web.archive.org/web/20250110131912/https://www.geeksforgeeks.org/react-js-useref-hook/
Open In App

ReactJS useRef Hook

Last Updated : 09 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

BERJAYA

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.
FeatureuseRefuseState
Triggers re-renderNoYes
Use caseAccessing DOM, persisting valuesHandling component state
Initial valueOptionalRequired


Next Article

Similar Reads

three90RightbarBannerImg