While working on a personal project, I implemented useRef. It is a hook provided by React and is the equivalent of createRef which is used with class components.

The useRef hook is a function that returns a mutable ref object whose .current property is initialized with an argument, (initialValue). The returned object will persist for the full lifetime of the component. (Hooks Reference)

const refContainer = useRef(initialValue);

The useRef hook served two primary uses in my project: accessing DOM nodes/elements and storing mutable information. Let’s explore how useRef can be implemented in your React application.

Accessing DOM nodes/elements

Before diving further, let’s first discuss what ref is. It is an attribute that is used either on an HTML element or a component tag. It provides us a way of referencing DOM nodes in React.

Here is an example of utilizing ref in a div element.

<div className="sample" ref={divRef}>Sample Div</div>

ref can also utilized inside of a React component but only with the render method of the parent component.

<DivComponent ref={divComponentRef} />

In regular Javascript, this would be the equivalent of the syntax,

const divElement = document.querySelector(".sample")

Example of useRef and ref

In React, the ref attribute will allow us to reference that element and provide us access to its methods. Below is an example of ref and useRef in a functional component.

import React, { useRef } from "react";

	const SampleComponent = () => {
	  const textInputRef = useRef(null);

	  const buttonClick = () => textInputRef.current.focus();

	  return (
	    <React.Fragment>
	      <input type="text" ref={textInputRef} />
	      <button onClick={buttonClick}>Focus on the text</button>
	    <React.Fragment/>
	  );
	}

	export default SampleComponent

#useref #javascript #react #react-hook #document-object-model #programming

Implementing useRef in React
4.20 GEEK