Skip to main content
InterviewHubPRO
Section Overview
Q322

Question 322 of 407

Part 9: React Hooks Deep Dive (262 - 316)

79%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

What is the use of refs?

junior LevelCode ExampleHooks

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>
  );
}