The useRef is an out-of-the-box hook in React 16.8. It is the functional component alternative to createRef() that is used in React’s class (stateful) components. Whether or not you are familiar with refs, createRef, or useRef, this article will guide you through the basics of getting started with this quite useful hook.

First off, there are two main uses for the useRef hook in a React functional component: accessing a DOM element and storing mutable information in the state without triggering a re-render of that component. We will take a look at an example of both of these and discuss some things to keep in mind along the way.

A note of caution

Generally, we should avoid using the useRef in React for anything that can be done declaratively - that is, we should let React handle the state of the app and the “how” of each component as much as possible. However, there are some situations where you need to imperatively alter or interact with a DOM element, telling it “how” to treat (or not treat) something, and therefore bypassing the state. Some common DOM element examples of this include managing focus on a particular element, selecting text, or media playback. We’ll also explore a few other reasons we may need to get imperative with React.

What is a ref?

In React, a ref is an attribute that can be used in either element tags or component tags themselves. A ref provides “a way to access DOM nodes or React elements created in the render method,” (Refs and the DOM). In vanilla JavaScript, we work with DOM elements by calling document.getElementById(), passing in the id of a given element. With refs in React, we no longer need to do this. The ref attribute will literally reference that element and give us access to it’s methods.

Here is an example of putting a ref in an input tag:

<input type="text" ref={textInput} />

We can also use a ref inside of a component (but only within the render method of a parent component):

<FormComponent ref={formRef} />

The ref attribute is the inspiration for the useRef but it is not the only reason to use this hook. Let’s get into the useRef a little more.

#useref #react #javascript #react-refs #react-hook #programming

An intro to refs and React Hooks
1.55 GEEK