9Refs

Refs are one of the most-often debated and controversial topics in React. Hundreds of blog posts and articles on the web will caution you to avoid refs. The official documentation for React even says (several times, in fact) that you should avoid using them, except in particular situations.

Knowing exactly when it's okay to use refs and what the problem is with using them is one of the things you'll pick up with more experience, but my aim in this chapter is to give you a head start on understanding why refs are such a hot-button issue, and some practical advice on how to use them correctly.

In this chapter, you'll learn:

  • How to use refs in class components.
  • How to use refs in function components.
  • When you should use refs.
  • When you shouldn't use refs.
  • How to maintain the correct focus in a form.

WHAT REFS ARE

Nothing is perfect, and that includes React. There are rare, but unavoidable, times when one-way data flow and the declarative way of only modifying children via props break down. In these cases, which I'll demonstrate in more detail and with plenty of examples in this chapter, a React developer needs to be able to imperatively get into a child component or a DOM node to make changes or access some property directly. For these cases, React provides an “escape hatch” called refs.

A ref is reference to a child component that allows you to modify a child component or DOM node from the parent component, rather than by using the standard method of modifying children ...

Get Beginning ReactJS Foundations Building User Interfaces with ReactJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.