Back to Blog
ReactforwardRefRefsComponents

React forwardRef Guide

Master React forwardRef for passing refs through components and building reusable component libraries.

B
Bootspring Team
Engineering
March 14, 2020
6 min read

forwardRef lets you pass refs through components to access child DOM elements. Here's how to use it.

Basic Usage#

Loading code block...

TypeScript Patterns#

Loading code block...

Custom Component Library#

Loading code block...

useImperativeHandle#

Loading code block...
Loading code block...

Polymorphic Components#

Loading code block...

HOC with forwardRef#

Loading code block...

Common Patterns#

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles