Back to Blog
ReactRefsCallbacksPatterns

React Ref Callback Pattern

Master React ref callbacks for dynamic refs, measuring elements, and complex ref scenarios.

B
Bootspring Team
Engineering
January 30, 2020
6 min read

Ref callbacks provide more control than useRef for dynamic scenarios. Here's how to use them.

Basic Ref Callback#

Loading code block...

Dynamic Element Lists#

Loading code block...

Focus Management#

Loading code block...

Intersection Observer#

Loading code block...

ResizeObserver#

Loading code block...

Animation Trigger#

Loading code block...

Third-Party Libraries#

Loading code block...

Merging Refs#

Loading code block...

Best Practices#

Usage: ✓ Use for measurement/observers ✓ Use for dynamic element lists ✓ Use for third-party integrations ✓ Wrap in useCallback when needed Cleanup: ✓ Handle null (element unmounted) ✓ Disconnect observers ✓ Dispose library instances ✓ Clear stored references Performance: ✓ Memoize with useCallback ✓ Avoid creating refs in loops ✓ Use Map for dynamic refs ✓ Batch state updates Avoid: ✗ Side effects without cleanup ✗ Recreating refs unnecessarily ✗ Forgetting null checks ✗ Complex logic in callbacks

Conclusion#

Ref callbacks provide fine-grained control for measuring elements, managing observers, and integrating third-party libraries. Use them when useRef isn't flexible enough, especially for dynamic lists and elements that need setup/cleanup logic. Always handle the null case for proper cleanup.

Share this article

Help spread the word about Bootspring

Related articles