Refs provide direct access to DOM elements and component instances. Here's how to use them effectively.
Basic useRef#
Callback Refs#
forwardRef#
useImperativeHandle#
Video Player Example#
Form Control Example#
Merging Refs#
Avoiding Common Pitfalls#
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.