React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
What is the use of refs?
The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.
Code Example
tsx
import React, { useRef } from 'react';
export function TextInputWithFocusButton() {
const inputEl = useRef<HTMLInputElement>(null);
const onButtonClick = () => {
// Directly focus the input element using DOM reference
inputEl.current?.focus();
};
return (
<div className="p-4 space-y-4">
<input ref={inputEl} type="text" className="border p-2 rounded" placeholder="Focus me..." />
<button onClick={onButtonClick} className="px-4 py-2 bg-blue-600 text-white rounded">
Focus the input
</button>
</div>
);
}