How to Implement React Refs in React

In React, Refs provide a direct way to access DOM nodes or React elements created in the render method. This article explains the fundamentals of React Refs, outlines when you should use them, and provides a step-by-step guide on how to implement them in modern functional components using the useRef hook, as well as in legacy class components.


What is a React Ref?

A Ref (short for reference) is a special object that holds a mutable value in its .current property. Unlike state variables, updating a ref does not trigger a component re-render. While React typically manages the DOM automatically through the Virtual DOM, refs allow you to bypass this and interact with actual HTML elements directly.

When to Use Refs

You should use refs sparingly and only for side effects that cannot be handled declaratively through state and props. Common use cases include: * Managing focus, text selection, or media playback (e.g., playing/pausing video). * Triggering imperative animations. * Integrating with third-party DOM-based libraries (like D3 or jQuery). * Measuring the size or position of a DOM node.


Implementing Refs in Functional Components

In modern React, you implement refs using the useRef Hook. Here is how to do it step-by-step:

Step 1: Import the Hook

Import useRef from the React package.

import React, { useRef } from 'react';

Step 2: Initialize the Ref

Call useRef inside your component and assign it to a variable. Pass an initial value (usually null for DOM elements) as the argument.

const inputRef = useRef(null);

Step 3: Attach the Ref to a DOM Element

Pass the ref variable to the ref attribute of the JSX element you want to target.

<input ref={inputRef} type="text" />

Step 4: Access the DOM Node

You can now access and manipulate the DOM node via inputRef.current.

Here is a complete example of using a ref to focus an input element when a button is clicked:

import React, { useRef } from 'react';

function FocusInput() {
  const inputElement = useRef(null);

  const handleFocus = () => {
    // Access the actual DOM node using .current
    inputElement.current.focus();
  };

  return (
    <div>
      <input ref={inputElement} type="text" placeholder="Click button to focus..." />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
}

export default FocusInput;

Implementing Refs in Class Components

If you are working with legacy codebase class components, you implement refs using React.createRef().

Step 1: Create the Ref in the Constructor

Initialize the ref inside the constructor of your class component and assign it to an instance property.

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

Step 2: Attach and Access the Ref

Attach the ref to the element in the render method and access it using this.textInput.current.

import React from 'react';

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

  focusTextInput = () => {
    this.textInput.current.focus();
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <button onClick={this.focusTextInput}>Focus Text Input</button>
      </div>
    );
  }
}

export default AutoFocusInput;