DEV Community

Aman Kureshi
Aman Kureshi

Posted on

📍 useRef in React — Access DOM or Store Mutable Values Without Re-rendering

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)