Open In App

React JS useRef Hook

Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will learn about the useRef hook in React, its implementation and uses with the help of an example

What is useRef hook?

The useRef is a hook that 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 about refs in React. Unlike useState if we change a value in useRef it will not re-render the webpage

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. 

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


Last Updated : 03 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads