The useRef hook is used to:
β’ Access and modify DOM elements directly
β’ Store mutable values that donβt cause re-renders
β’ Persist values between renders
π§ DOM access example:
import { useRef } from "react";
function InputFocus() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
π§ Store value without re-rendering:
const countRef = useRef(0);
countRef.current += 1;
console.log(countRef.current);
π Key points:
β’ useRef() returns a .current object
β’ Updating .current doesnβt trigger re-render
β’ Perfect for timers, focus control, or keeping previous values
useRef is a powerful tool when you need to interact with the DOM or avoid unnecessary renders.
Top comments (0)