Migrating DOM refs from createRef() to useRef()

Jamund Ferguson
InstructorJamund Ferguson

Share this video with your friends

Send Tweet

In this lesson we replace React.createRef() with the React.useRef hook. The API is almost identical, so the there's not much to it, if you're already familiar with refs.

In React, refs provide a way to store references to native DOM elements. Throughout React's evolution there have been several variations on the pattern including callback refs and string refs. With functional components you'll only want to be using the useRef() hook to create your refs.

One other thing to note about refs is that you can only pass them in to class components and built-in components (such as <div>). If you need to pass a ref into a function components check out the forwardRef API.


Callback Refs

This lesson does not cover callback refs, but if you have one like this one and you wanted to migrate it to useRef()

class MyComponent extends React.Component {
   render() {
      return (
        <input type="text" ref={el => this.inputRef = el} />
      )
   }
}

It would look like this:

function MyComponent() {
   const inputRef = useRef();
   return <input type="text" ref={inputRef} />
}

Jamund Ferguson: [0:00] Open up RateTable.js. At the top of the file, import { useRef } from "react". Convert the class component to a function component. Type export function RateTable. Get rid of extends and replace it with the parentheses. Comment out the constructor. Take the render() function and turn it into the function body.

[0:22] In the other methods, such as the bounce() method here, we'll just turn into function declarations. We need to take our props and inline them in our function declaration. Any references that rely on this we'll remove, this.bounce, this.nameRef, and down here, this.nameRef.current.

[0:41] With those changes made, we now see that our app is complaining that nameRef is not defined. Type const nameRef = useRef().

[0:51] The important difference here between useRef and createRef is simply that useRef is a hook and it's used in function components, whereas createRef is used for class components. That's really the only difference.

[1:04] Once you have your ref, such as nameRef here, you can pass it into elements using the ref prop. You can access the current instance with ref.current, as we do here, in our bounce.applyTo() method.

[1:18] The API is exactly the same as it was before, except it's not going to be saved as an instance variable. Instead, it's going to be created with our useRef hook.

[1:26] With that, get rid of the constructor, and you can see our beautiful bounce function still works as it did before.