React.createRef vs React.useRef

Thursday, March 3, 2022 min read

What is a ref?

A ref is defined as any value that does not trigger a component re-render when it is changed. A ref can be created with React.useRef() hook or by the React.createRef() function.

React.createRef

The React.createRef() is a function that creates a new ref every time, it does not save its value between re-renders, instead creates a new instance of the ref for every re-render.

On class refs are created using React.createRef() and attached to React elements via the ref attribute, are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
    }
    render() {
        return <div ref={this.myRef} />;
    }
}

Accessing Refs

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

const node = this.myRef.current;

The value of the ref differs depending on the type of the node:

  • When the ref attribute is used on an HTML element, the ref created in the constructor with React.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.

React.useRef

The React.useRef() is a hook that uses the same ref throughout, it saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render.

You can, however, use the ref attribute inside a function component as long as you refer to a DOM element.

function CustomTextInput(props) {
    const textInput = useRef(null);

    function handleClick() {
        textInput.current.focus();
    }

    return (
        <div>
            <input type="text" ref={textInput} />
            <input
                type="button"
                value="Focus the text input"
                onClick={handleClick}
            />
        </div>
    );
}

Conclusion

The difference is that React.createRef() will always create a new ref in a class-based component, React.useRef() takes care of returning the same ref each time as on the initial rendering.