Refs on Built-in Components vs Custom Components
You'll learn: Why you can attach refs directly to native HTML elements, but custom components need special handling.
When you use the ref prop on built-in HTML elements like <div>, <input>, or <button>, React automatically gives you access to the actual DOM node. It just works:
function MyComponent() {
const inputRef = useRef(null);
// This works perfectly — ref gets the DOM element
return <input ref={inputRef} />;
}
But try the same thing with your own custom component, and you'll get null:
function CustomInput(props) {
return <input {...props} />;
}
function Parent() {
const ref = useRef(null);
// This WON'T work — ref.current will be null!
return <CustomInput ref={ref} />;
}
Why the Difference?
Built-in elements like <input> are primitives — React knows exactly what DOM node to hand you. But your custom components are just JavaScript functions. When you write <CustomInput />, React doesn't know which element inside that component you want to reference. The input? A wrapper div? Something else?
By default, React doesn't pass the ref prop through to your custom components at all. It's reserved for React's internal use.
The Analogy
Think of built-in components like ordering from a menu with pictures — the waiter knows exactly what to bring you. Custom components are like ordering "the chef's special" — without more information, there's no single obvious item to deliver.
Key Takeaway: Refs work automatically on native HTML elements because React knows what they represent, but custom components need explicit forwarding (which you'll learn next) to expose their internal elements.