Back to Blog
ReactforwardRefRefsComponents

React forwardRef Patterns Guide

Master React forwardRef for passing refs through components to access DOM elements and child methods.

B
Bootspring Team
Engineering
June 20, 2019
6 min read

forwardRef allows components to receive a ref and forward it to a child element. Here's how to use it effectively.

Basic Usage#

Loading code block...

With Additional Props#

Loading code block...

Composing Components#

Loading code block...

With useImperativeHandle#

Loading code block...

Multiple Refs#

Loading code block...

Generic forwardRef#

Loading code block...

With Higher-Order Components#

Loading code block...

Ref Callback Pattern#

Loading code block...

Input Group Component#

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles