QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Intermediate 16 min readModule: Module 7: Refs & DOM Manipulation (useRef)

useRef & Imperative DOM Access

Access browser DOM elements directly (focus, scroll, measurement) and store mutable values without triggering re-renders.

What You Will Learn in This Lesson

  • Creating ref containers with const ref = useRef(initial)
  • Focusing inputs and measuring bounding rectangles imperatively
  • Storing previous values and timer IDs across renders

Introduction & Core Concept

useRef returns a mutable ref object whose .current property is initialized to the passed argument. Mutating .current does NOT trigger a component re-render.
WHY DOES THIS MATTER IN THE REAL WORLD?

useRef is the standard React escape hatch for focusing inputs, triggering animations, or integrating third-party canvas libraries.

Auto-Focus Input with useRef

javascript
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function SearchInput() {
const inputRef = React.useRef(null);
const handleFocus = () => {
inputRef.current?.focus();
};
return (
<div>
<input ref={inputRef} placeholder="Search documentation..." />
<button onClick={handleFocus}>Focus Search (Ctrl+K)</button>
</div>
);
}

Line-by-Line Technical Breakdown

1Unlike useState, changing a ref value does not cause React to re-execute the component.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[JAVASCRIPT]
JAVASCRIPT SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Do not read or write ref.current during rendering; use refs only inside event handlers or effects.

Lesson Summary & Core Takeaways

  • useRef bridges declarative React with imperative DOM manipulation.