Ref forwarding passes a ref through a component to a child element. Here's how to use it effectively.
Basic Ref Forwarding
With TypeScript
Button Component
Forwarding to Multiple Elements
Custom Modal
Scroll Container
Video Player
Higher-Order Component
Compound Components
Best Practices
When to Use:
✓ Wrapping DOM elements
✓ Building component libraries
✓ HOC that wrap components
✓ Compound components
useImperativeHandle:
✓ Expose limited API
✓ Custom methods
✓ Multiple element refs
✓ Complex interactions
TypeScript:
✓ Specify element type
✓ Define custom handle type
✓ Extend HTML attributes
✓ Document exposed methods
Avoid:
✗ Exposing entire DOM node
✗ Overusing imperative APIs
✗ Forgetting displayName
✗ Complex ref hierarchies
Conclusion
Ref forwarding enables passing refs through components to DOM elements. Use forwardRef for simple cases, combine with useImperativeHandle to expose custom APIs. This pattern is essential for component libraries, accessibility, and integrating with third-party libraries that need DOM access. Keep exposed APIs minimal and well-documented.