Course contentsShow
← React
Lesson 731 of 2,39619. useRefFree lesson

When NOT to Forward Refs

Recognizing when ref forwarding breaks encapsulation or when callbacks are better.

When NOT to Forward Refs

You'll learn when forwarding refs actually harms your component design and when alternative patterns work better.

The Encapsulation Problem

Forwarding refs gives parent components direct access to your component's internals. This breaks encapsulation—the principle that a component should hide its implementation details. When you forward a ref, parents can reach inside and manipulate DOM nodes or call methods directly, bypassing your component's intended API.

Think of it like giving someone the keys to your car's engine compartment. Sure, they can adjust the carburetor directly, but should they? Or should you provide a simple "increase speed" interface instead?

When to Avoid forwardRef

Don't forward refs when:

  • Your component might change its internal structure later (which DOM node should the ref point to?)
  • You want to control how parents interact with your component
  • The component manages complex internal state that external imperative calls could break
  • A simple callback prop like onReady or onMount would work better

The Callback Alternative

Instead of forwarding a ref so parents can call .focus(), consider:

function TextField({ onMount }) {
  const inputRef = useRef(null);
  
  useEffect(() => {
    if (onMount) {
      onMount(inputRef.current);
    }
  }, [onMount]);
  
  return <input ref={inputRef} />;
}

Now the parent gets access only when you decide, and you control what gets exposed.

The Rule of Thumb

Forward refs for simple, stable wrapper components around DOM elements. Don't forward refs for complex components with internal logic—expose a controlled API instead (using props, callbacks, or useImperativeHandle if necessary).

Key Takeaway: Forwarding refs trades encapsulation for convenience. Only do it when the component is a thin wrapper around a DOM element, not when it has meaningful internal behavior you want to protect.