So how should I create ref in React

Shonn Lyga
PoZeCode
Published in
1 min readAug 23, 2018

TL;DR — Prefer using the latest API built in to the framework:

this.myRef = React.createRef()

While I appreciate the efforts by the React team to improve the framework, from purely user’s perspective this always reminds me of The Paradox of Choice.

Seems like now we have 3 different ways to create refs in React:

  1. String ref:
<div ref="foo2" />

2. By callback:

<div ref={this.divRef} />

3. By API call:

this.myRef = React.createRef();

So which one should you use? The first one is considered deprecated by React. The second one should be used only when there is a very good reason for it (for example hooking in to the execution exactly when the ref is assigned or removed).

So if you have no good reason to use the callback ref creation, you should always default to the 3'rd and most straightforward option.

--

--