Kevin Moe Myint Myat
Kevin Moe Myint Myat

Reputation: 2185

What are the advantages for using useRef or createRef rather than inline ref?

I was doing a code review and found the code written by another developer such as:

function sampleComponent() {
       let divRef = {};
    
       return (
        <div ref={(el) => { divRef = el }}></div>
       )
    }

And then use the divRef as a reference to DOM element.

However, the pattern that I know is using createRef in class component and useRef hook in functional component. Even the ReactJS official https://reactjs.org/docs/refs-and-the-dom.html said to avoid inline ref for future React version. Is it a legacy pattern to write?

So far what I can research is, inline ref will render the function two times, therefore it is recommended to avoid.

I was wondering what are the other explanation available for this?

Upvotes: 4

Views: 1706

Answers (2)

Yoandry Collazo
Yoandry Collazo

Reputation: 1212

Two details to have in mind

Legacy API: String Refs If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

This no means inline Ref, this means String Ref, inline ref could be a callback pattern. Until this point, this only means that String Ref is not recommended to use because is legacy and going to be removed in the near future. Actually react use as reference functions or more complex objects to allow advance usages.

Caveats with callback refs If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.

Here the point against callback pattern. Reacts need to call twice the function because the first need to clear the reference then assigns the new value.

This is only a performance recommendation, is not a big deal but is a warning flag because there are other ways more efficiently.

Upvotes: 1

Yuan-Hao Chiang
Yuan-Hao Chiang

Reputation: 2613

I think what they recommend is to not use string refs as it's a legacy API. There is no mention about inline refs being not recommended. As you mentioned, callback refs / inline refs call the functions multiple times and that might be their main caveat.

In any case I think if there is no granularity required, createRef or useRef are more of a "best-practice".

For me, I try to stay with createRef and useRef as they use myRef.current (as opposed to just myRef), in order to avoid getting confused by it.

Upvotes: 5

Related Questions