reactjsrefuse-refcreate-ref

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?


Solution

  • 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.