useRef() Hook

useRef() Hook is one of the standard hooks provided by React. It will return an object that can be used during the whole lifecycle of the component.

The main use case for the useRef hook() is to access the DOM child directly.

As we have seen, accessing the DOM is the main use case, it doesn’t mean it’s the only one! useRef() can be very useful to hold a mutable value across different renders of your component.

Reactjs.org defines useRef Hook() as :-

Syntax :-

const refContainer = useRef(initialValue);

When to use useRef Hook()?

In React components, there can be a need to track the frequent changes without enforcing the re-rendering of the component. It can also be that there might be a need to re-render the component efficiently. While useState and useReducer hooks are the React API to manage local state in a React component, they can also come at the cost of being called too often making the component to rerender for each call made to the update functions.

How to access DOM using useRef hook()?

import React, {Fragment, useRef} from 'react';

function App() {


const focusPoint = useRef(null);
const onClickHandler = () => {
focusPoint.current.value =
"Hello from team PLG";
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:

We have an ACTION button, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with help of useRef hook(). The focusPoint is the useRef object which is initialized to null and the value is changed to onClick event.

Summing up :-

We can use the useRef Hook() to create mutable variables inside functional components. There are three main key points that one should keep in mind while using the useRef Hook():

  • A ref created using useRef() will be created only when the component is preserved for a full lifecycle and has already been mounted.
  • DOM nodes or React elements can be accessed using Refs, and mutable variables (like with instance variables in class components) can also be stored using Refs.
  • Updating a ref should only be done inside a useEffect (or useLayoutEffect) or inside an event handler as it is a side effect.
Parv Saxena

Parv Saxena