What are React refs?

React refs are used to access the DOM or React elements that were created in the render method. According to the official documentationhttps://legacy.reactjs.org/docs/refs-and-the-dom.html, refs should be used to:

  1. Manage focus, media playback, or text selection.
  2. Integrate with third-party DOM libraries.
  3. Trigger animations.

Three ways used to create refs in React are:

  • string refs (this method is deprecated)
  • callback refs
  • createRef() refs (this is a recent addition)

Code

In the examples below, a ref is used to access the user input and set the background color to a specified color.

1. Using callbacks

The following code snippet demonstrates how a ref can be created using a callback:

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

2. Using createRef()

Starting from version 16.3, React included a new createRef() method that can be used for creating refs. The following code snippet demonstrates how a ref can be created using the createRef() method:

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved