How does React.createRef() actually work?

How does React.createRef() actually work?

React.createRef()

createRef() receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current .

The above description is what documentation says.

I can't tell about you but I need for information to really understand How does it actually work?

Let's have a look on below component.

import React, { Component } from "react";

class ImageCard extends Component {
  constructor(props) {
    super(props);
    this.imageRef = React.createRef();
    console.log("Called in constructor", this.imageRef);
  }

  componentDidMount() {
    console.log("Called when component did mount ", this.imageRef);
  }

  render() {
    const { description, urls } = this.props.image;
    return (
      <div>
        <img ref={this.imageRef} src={urls.regular} alt={description} />
      </div>
    );
  }
}

export default ImageCard;

So, in the constructor I created a React Ref, and assigned to a property called imageRef.

And, in the render() method, I passed that React Ref to img React element as an attribute as a ref.

What does React Ref does here?

For how ref gets assigned, you have to remember that JSX compiled down to plain old javascript. A very simplified example of what is going on under the covers is something like this:

function createRef(initialValue) {
    return {
        current: initialValue
    }
}

const root = document.getElementById('root');

function render(elementType, innerText, ref) {
    const el = document.createElement(elementType);
    if (ref) {
        ref.current = el;
    }
    el.innerText = innerText;
    root.replaceChildren(el);
}

const ref = createRef(null);
console.log(ref);
render('div', 'Hello World', ref);
console.log(ref);

So basically - when we use

<img ref={this.imageRef} src={urls.regular} alt={description} />

the ref is passed as a property, and in the function that renders it, it assigns the actual DOM node to ref.current.

Did you find this article valuable?

Support Sujeet Agrahari by becoming a sponsor. Any amount is appreciated!