In this article, we will see what is the major difference between useRef and createRef along with some examples and when to use each one.

createRef

createRef is used in the class components to create and manage the references to the DOM elements.

Earlier, to access the DOM elements in the class components, we were using the callback patterns. createRef was introduced as a replacement for the callback pattern.

To use createRef, we need to create a new ref object in the constructor of the class component using the React.createRef, then attach it to a DOM element using the ref attribute. We can then access the current value of the ref object to manipulate the DOM element.

Following is an example of how to use createRef in a class component

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.myInput = React.createRef();
  }

  focusInput = () => {
    this.myInput.current.focus();
  };

  render() {
    return (
      <div>
        <input ref={this.myInput} />
        <button onClick={this.focusInput}>Focus Input</button>
      </div>
    );
  }
}

useRef

After introduction of react hooks, the functional components got the ability to manage states and make them more flexible than the class based components. Like the createRef in class based components, the useRef hook allows the functional components to create an manage the references to the DOM elements.

The useRef returns a mutable ref object with a current property initialized to the argument passed to it. The current property of the useRef can be used to store any mutable value and not just the DOM elements.

Like the createRef, we can attach the ref object to a DOM element using the ref attribute.

useRef returns a mutable ref object with a current property initialized to the argument passed to it. The current property can be used to store any mutable value, not just DOM elements. Like createRef, you can attach the ref object to a DOM element using the ref attribute.

Following is the example on how to use the useRef in functional component:

import React, { useRef } from 'react';

function MyComponent() {
  const myInput = useRef(null);

  const focusInput = () => {
    myInput.current.focus();
  };

  return (
    <div>
      <input ref={myInput} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

Categorized in:

Tagged in: