forwardRef lets you pass refs through components to access child DOM elements. Here's how to use it.
Basic Usage#
TypeScript Patterns#
Custom Component Library#
useImperativeHandle#
Modal with Ref#
Polymorphic Components#
HOC with forwardRef#
Common Patterns#
Best Practices#
Usage:
✓ Use for reusable component libraries
✓ Expose DOM refs when needed
✓ Use useImperativeHandle sparingly
✓ Add displayName for debugging
TypeScript:
✓ Type refs properly
✓ Extend native element props
✓ Use ComponentPropsWithoutRef
✓ Document custom ref APIs
Patterns:
✓ Forward refs in HOCs
✓ Merge internal and forwarded refs
✓ Keep ref APIs minimal
✓ Prefer props over imperative
Avoid:
✗ Overusing imperative patterns
✗ Exposing too much via ref
✗ Forgetting to forward refs
✗ Complex ref dependencies
Conclusion#
forwardRef enables passing refs through components to access underlying DOM elements. Use it for building component libraries, custom inputs, and any reusable component that wraps native elements. Combine with useImperativeHandle when you need custom imperative APIs, but prefer declarative patterns when possible.