javascriptreactjsuse-refcreate-ref

Why behavior is different?


What's the difference between createRef and ref={(c) => this.el = c}?

When I output each ref has same element but it not false.

why?

import React from "react"

class Home extends React.Component {
constructor(){
  super();
  this.el1 = React.createRef();
}

componentDidmount(){
  console.log(el1 === el2) // false   why false?
}

render(){
  return (
    <>
      <div ref={this.el1}>
        <span>A</span>
      </div>
      <div ref={(c)=> { this.el2 = c }}}>
        <span>A</span>
      </div>
    </>
  )
}

Solution

  • In the code both ref are pointing to two different DOMnodes that's why these are not same.

    createRef is returning either a DOM node or a mounted instance of a component, depending on where you call it. Either way, what you have in hand is indeed straightforward as you've noted. But what if you want to do something with that reference? What if you want to do it when the component mounts?

    Ref callbacks are great for that because they are invoked before componentDidMount and componentDidUpdate. This is how you get more fine-grained control over the ref. You are now not just grabbing DOM elements imperatively, but instead dynamically updating the DOM in the React lifecycle, but with fine-grained access to your DOM via the ref API.