Refs provide direct access to DOM elements and persist values across renders. Here's how to use them.
Basic useRef
Loading code block...
forwardRef
Loading code block...
useImperativeHandle
Loading code block...
Ref Callbacks
Loading code block...
Combining Multiple Refs
Loading code block...
Ref with Intersection Observer
Loading code block...
Previous Value Ref
Loading code block...
Latest Value Ref
Loading code block...
DOM Manipulation
Loading code block...
Canvas Ref
Loading code block...
Best Practices
Usage:
✓ Use refs for DOM access
✓ Store mutable values that don't trigger renders
✓ Use forwardRef for reusable components
✓ Prefer controlled components when possible
Patterns:
✓ useImperativeHandle for custom API
✓ Callback refs for measurement
✓ Merge refs when needed
✓ Keep refs stable
Avoid:
✗ Overusing refs for state
✗ Directly mutating DOM in render
✗ Ignoring null checks
✗ Creating refs in loops without keys
Conclusion
Refs enable direct DOM access and mutable value storage. Use forwardRef for component composition, useImperativeHandle for custom APIs, and callback refs for dynamic scenarios. Always handle null cases and prefer React's declarative patterns when possible.