javascriptreactjsecmascript-6react-refcreate-ref

Why not use own object with current property rather than createRef in ReactJs


In ReactJs documentation, it is said

Refs are created using React.createRef() and attached to React elements via the ref attribute

Logging the ref gives an object which has a current property set to null. Just out of curiosity, I created a normal object with current property and tried to use it as a ref. Following is the test case and it somehow works:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);    
    this.myRef = {}; //Works!!!
    //console.log(React.createRef());
    //bind
    this.RefFocus = this.Myfocus.bind(this);
  }
  componentDidMount() {
    console.log(this.myRef.current);
  }
  Myfocus() {
    this.myRef.current.focus();
  }


  render() {
    return (
      <div>        
        <input
          type="text"
          ref={this.myRef} />
        <input
          type = "button"
          value = "Focus the text input"
          onClick = {this.RefFocus}
        />        
      </div>
    );
  }
}

//const app = ReactDOM.createRoot(document.getElementById("app"));
ReactDOM.render(<CustomTextInput />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

So the question is, why do we need the createRef api at all? Is there something special that React does with createRef, e.g. better performance, memory optimization etc or are there cases like ref forwarding where a custom {current: null} wouldn't work?

Please explain in easy language, I am new to React and JavaScript.


Solution

  • CreateRef is just a wrapper to simplify writing and reading code

    The createRef implementation looks like this (source code react):

    export function createRef() {
      const refObject = {
        current: null,
      };
      return refObject;
    }