useRef is a React Hook used to store a value or directly access a DOM element without causing a re-render.
Syntax:
import { useRef } from "react";
const myRef = useRef(null);
Example:
Focus on Input
import React, { useRef } from "react";
function App() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
Focus Input
</>
);
}
export default App;
Explanation:
- useRef(null) – Creates a reference.
- ref={inputRef} – Connects the reference to the input.
- inputRef.current – Accesses the input element.
- .focus() – Automatically focuses the input.
