Back to Blog
ReactRefsDOMComponents

React Refs and Forwarding

Master refs in React. From useRef to forwardRef to imperative handles and DOM access.

B
Bootspring Team
Engineering
September 26, 2020
7 min read

Refs provide direct access to DOM elements and component instances. Here's how to use them effectively.

Basic useRef#

Loading code block...

Callback Refs#

Loading code block...

forwardRef#

Loading code block...

useImperativeHandle#

Loading code block...

Video Player Example#

Loading code block...

Form Control Example#

Loading code block...

Merging Refs#

Loading code block...

Avoiding Common Pitfalls#

Loading code block...

Best Practices#

When to Use Refs: ✓ DOM element access (focus, scroll, measure) ✓ Storing timeout/interval IDs ✓ Storing previous values ✓ Imperative animations ✓ Third-party library integration When NOT to Use Refs: ✗ Data that affects rendering (use state) ✗ Avoiding re-renders (consider memo) ✗ Storing component state ✗ Communication between components forwardRef: ✓ Use for reusable components ✓ Add displayName for debugging ✓ Document exposed ref API ✓ Consider useImperativeHandle useImperativeHandle: ✓ Expose minimal API ✓ Hide implementation details ✓ Type the handle interface ✓ Include cleanup in return

Conclusion#

Refs provide escape hatches for DOM access and imperative operations. Use useRef for direct element access, forwardRef to pass refs through components, and useImperativeHandle to expose custom APIs. Remember that refs don't trigger re-renders and should be accessed in effects or event handlers.

Share this article

Help spread the word about Bootspring

Related articles