SoFunction
Updated on 2025-04-13

Summary of the role of Ref in React

1. The basic concept of Ref

Ref is an interface provided by React that allows us to access DOM nodes or component instances created during rendering. It is usually used in cases where direct manipulation of the DOM or accessing the internal state of the component. It is worth noting that Ref does not belong to a part of React's data stream, so its changes do not trigger re-rendering of components.

2. How to use Ref

createRef method

React 16.3 introduces the createRef method, which allows us to create a mutable Ref object and assign it to a class attribute. This Ref object has a current property that points to the referenced DOM node or component instance.

class MyComponent extends  {
  constructor(props) {
    super(props);
     = ();
  }
 
  focusInput = () => {
    ();
  };
 
  render() {
    return (
      <div>
        <input type="text" ref={} />
        <button onClick={}>Focus input box</button>
      </div>
    );
  }
}

useRef in function component

In function components, since they have no instances, they cannot be used directly to access Refs. However, React provides a useRef hook, which allows us to create and use Refs in function components.

import React, { useRef } from 'react';
 
const MyFunctionComponent = () => {
  const inputRef = useRef(null);
 
  const focusInput = () => {
    if () {
      ();
    }
  };
 
  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={focusInput}>Focus input box</button>
    </div>
  );
};

Callback function Ref

The callback function Ref is a more flexible and recommended way of use. By providing a callback function, we can execute custom logic when the Ref is set or updated.

class MyComponent extends  {
  constructor(props) {
    super(props);
     = null;
  }
 
  setMyInputRef = (element) => {
     = element;
  };
 
  focusInput = () => {
    if () {
      ();
    }
  };
 
  render() {
    return (
      <div>
        <input type="text" ref={} />
        <button onClick={}>Focus input box</button>
      </div>
    );
  }
}

3. The problem of ref operating value but component not updating

In React, component updates are usually triggered by changes in state or properties. When using ref to directly manipulate the value of the component, React does not know that this value has changed because ref bypasses React's responsive update mechanism. React's update mechanism is based on virtual DOM comparisons. React will re-render components only when state or props change.
In function components, we usually use React's useState and useRef hooks to manage state and references. Similar to class components, modifying the state directly through Ref usually does not trigger re-rendering of the component. This is because Ref is mainly used to directly access DOM elements or component instances, rather than to manage state.

Give an example

import React, { useState, useRef } from 'react';

const SimpleInputComponent = () => {
  const [inputValue, setInputValue] = useState(0); // React status  const inputRef = useRef(0); // DOM Quotation
  // Process the input box changes and update the React status  const handleInputChange = (event) => {
    setInputValue();
  };

  // Modify the DOM value directly through Ref (not recommended)  const forceUpdateDOMValue = () => {
    if () {
       = 1;
      // Note: Although the DOM value has changed here, the React state inputValue has not changed    }
  };

  // Update status through useState (recommended)  const updateStateValue = () => {
    setInputValue(2);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue} // The React state is bound here        onChange={handleInputChange} // React status will be updated when changes are made        ref={inputRef} // Bind DOM reference      />
      <button onClick={forceUpdateDOMValue}>passRefModify directlyDOMvalue</button>
      <button onClick={updateStateValue}>passuseStateUpdate status</button>
      <p>currentReact状态value:{inputValue}</p>
    </div>
  );
};

export default SimpleInputComponent;

In this example, we have an input box and two buttons. When you enter text, the React state inputValue is updated and the component is re-rendered to reflect the new state. However, when you click the "Modify DOM value directly through Ref" button, although the DOM value of the input box is changed, the React state inputValue has not changed, so the React state value displayed on the page will not be updated. Instead, when you click the "Update status via useState" button, the React status inputValue is updated and the component is re-rendered to display the new status value.

This is the end of this article about the role of Ref in React. For more related React Ref content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!