Accessing current After Mount
You'll learn why ref.current is null during the initial render and only becomes available after the component mounts.
The Timing Gap
When you attach a ref to a DOM element using the ref prop, React doesn't populate ref.current immediately. During the component's initial render, React is building up the virtual representation of your UI—the actual DOM nodes don't exist yet. Only after React finishes rendering and commits those elements to the real DOM does it go back and assign the DOM nodes to your refs.
Think of it like ordering furniture online: when you place the order (render), you don't immediately have the furniture (DOM node). You have to wait for delivery (mount) before you can sit on it (access ref.current).
The Practical Implication
If you try to read ref.current during render (in the component body), it will be null. This is why refs are commonly accessed in:
useEffectwith an empty dependency array – runs after mount- Event handlers – run after user interaction (which happens after mount)
- Other effects – also run after the DOM is ready
function MyComponent() {
const inputRef = useRef(null);
// ❌ This will log null on first render
console.log(inputRef.current);
useEffect(() => {
// ✅ This logs the actual <input> element
console.log(inputRef.current);
}, []);
return <input ref={inputRef} />;
}
Key Takeaway: ref.current is null during render and only becomes populated after React mounts the component to the DOM—access it in effects or event handlers, not during the render phase.