What is useRef in React?
useRef
is a React hook that provides a way to persist values between renders without causing a re-render.
It returns a mutable ref
object with a .current
property, which you can use to store a DOM reference or any mutable value.
import { useRef } from "react";
function Example() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // Accesses the DOM node directly
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}