forwardRef allows components to receive a ref and forward it to a child element. Here's how to use it effectively.
Basic Usage#
With Additional Props#
Composing Components#
With useImperativeHandle#
Multiple Refs#
Generic forwardRef#
With Higher-Order Components#
Ref Callback Pattern#
Input Group Component#
Best Practices#
Typing:
✓ Use proper generic types
✓ Set displayName for debugging
✓ Type both ref and props
✓ Export prop types
Patterns:
✓ useImperativeHandle for custom APIs
✓ Combine refs when needed
✓ Support ref callbacks
✓ Forward to correct element
Component Design:
✓ Keep ref forwarding simple
✓ Document ref behavior
✓ Consider if ref is needed
✓ Use composition
Avoid:
✗ Forwarding to wrong element
✗ Forgetting displayName
✗ Complex ref logic
✗ Breaking ref contract
Conclusion#
forwardRef enables passing refs through components to access DOM elements or expose imperative APIs. Use it with useImperativeHandle for custom ref interfaces, combine with useCallback for measurement patterns, and properly type both the ref and props. Always set displayName for easier debugging in React DevTools. Consider whether a ref is necessary, as declarative patterns often work better.