Skip to content

ReactJS - Refs

Refs provide a way to access DOM nodes or React components created in the render method. While you should generally avoid using refs for anything that can be done declaratively (i.e., via props and state), they can be useful for managing focus, text selection, media playback, triggering imperative animations, or integrating with third-party DOM libraries. The primary way to use refs in functional components is with the useRef hook. For more information, see the [Link to React Docs on Refs and the DOM].

The useRef hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. You can attach this ref to a DOM element via the ref attribute in JSX. This allows you to directly interact with the DOM element.

import React, { useState, useRef } from 'react';
function App() {
const [inputValue, setInputValue] = useState('');
const inputRef = useRef(null); // Create a ref
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
const clearAndFocusInput = () => {
setInputValue(''); // Clear the input's value via state
// Access the DOM element using inputRef.current
if (inputRef.current) {
inputRef.current.focus(); // Focus the input field
}
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
ref={inputRef} // Attach the ref to the input element
/>
<button onClick={clearAndFocusInput}>CLEAR AND FOCUS</button>
<h4>Current Value: {inputValue}</h4>
</div>
);
}
export default App;
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);

In this example, when the ‘CLEAR AND FOCUS’ button is clicked, the clearAndFocusInput function is called. It first updates the state inputValue to an empty string (which clears the input field because its value is controlled by this state). Then, it uses inputRef.current.focus() to programmatically set focus to the input element. inputRef.current directly refers to the underlying DOM input node.

Note: String refs are legacy and should be avoided. ReactDOM.findDOMNode() is also discouraged for most use cases and has been deprecated in StrictMode. The useRef hook combined with the ref attribute on elements is the modern and recommended approach for accessing DOM nodes in functional components.