How to Use React Refs
How to utilise refs in React, with ref forwarding, callback refs and HOCs
React Refs are a useful feature that act as a means to reference a DOM element or a class component from within a parent component. This then give us a means to read and modify that element.
Perhaps the best way to describe a ref is as a bridge; a bridge that allows a component to access or modify an element a ref is attached to. Using refs give us a way to access elements while bypassing state updates and re-renders; this can be useful in some use cases, but should not be used as an alternative to props and state (as the official React docs point out). Nevertheless, refs work well in certain scenarios that we will visit in this article.
Refs also provide some flexibility for referencing elements within a child component from a parent component, in the form of ref forwarding — we will also explore how to do this here, including how to inject refs from HOCs into their wrapped components.
Refs at a high level
Refs are usually defined in the constructor of class components, or as variables at the top level of functional components, and then attached to an element in the render()
function. Here is a bare-bones example where we are creating a ref and attaching it to an…