The useRef Hook — Secret Data Storage
Imagine your component is an actor on stage. Every time decorations change (state), the actor replays the entire scene. But what if the actor needs to hide a cheat sheet in their pocket that they can pull out at any moment without interrupting the performance? useRef is exactly such a " pocket " .
1. Main Secret: Silence
Unlike useState, changing useRef doesn't cause redraw.
- This means if you update
ref.current = 10, the user sees nothing on screen. - Why is this needed? For storing technical data that doesn't affect appearance: timer IDs, previous prop values, or references to DOM elements.
2. Direct DOM Access (Forbidden Technique)
React works on the principle: " I'll draw everything myself, don't touch the browser with your hands " . But sometimes we have no choice.
You'll need useRef for:
- Focus: Immediately put cursor in an input field when page opens.
- Measurements: Find the exact width or height of an image in pixels.
- Third-party libraries: If you're connecting Google Maps, video player, or complex animation (GSAP), they need a real " piece " of HTML, not a virtual React component.
const inputRef = useRef(null);
const handleClick = () => {
// We directly access the browser <input> element
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>Set focus</button>
</>
);
3. What NOT to Do with useRef?
Never use ref.current inside the markup itself (in JSX).
- ❌ Bad:
<div>{myRef.current}</div>. If the value in ref changes, text on screen will remain old. - ✅ Rule: Read and write to refs only inside useEffect or in event handlers.
useRef is your " emergency exit " from the reactivity world. Use it wisely to connect with the real browser world.