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
- Manage focus, media playback, or text selection.
- Integrate with third-party DOM libraries.
- 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 ©2026 Educative, Inc. All rights reserved