Ref callbacks provide more control than useRef for dynamic scenarios. Here's how to use them.
Basic Ref Callback#
Dynamic Element Lists#
Focus Management#
Intersection Observer#
ResizeObserver#
Animation Trigger#
Third-Party Libraries#
Merging Refs#
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.