Overview
Refs provide a way to access DOM nodes or React elements created in the render method. They’re useful for managing focus, text selection, media playback, triggering animations, and integrating with third-party DOM libraries.Creating Refs
Using useRef Hook
TheuseRef hook is the modern way to create refs in function components:
API Signature
Frompackages/react/src/ReactHooks.js:82:
.current property is initialized to the passed argument.
Using createRef (Class Components)
Frompackages/react/src/ReactCreateRef.js:
Forwarding Refs
ForwardRef allows components to pass refs through to their children. This is useful when building reusable component libraries.API Signature
Frompackages/react/src/ReactForwardRef.js:12:
Basic Example
Advanced ForwardRef with useImperativeHandle
Customize the instance value that is exposed to parent components:Callback Refs
Callback refs give you more control over when refs are set and unset:Practical Use Cases
Managing Focus
Text Selection
Scroll Management
Third-Party Library Integration
Refs with Mutable Values
Refs can store any mutable value, not just DOM nodes:Storing Previous Values
ForwardRef Implementation Details
Frompackages/react/src/ReactForwardRef.js:51:
Best Practices
- Avoid overusing refs: Use props and state for data flow when possible
- Don’t access refs during render: Refs are for side effects, not rendering logic
- Use callback refs for dynamic elements: When the ref target may change
- Clean up side effects: Always clean up intervals, listeners, etc. in useEffect cleanup
- Type your refs: Use TypeScript or JSDoc to specify ref types
- Combine with useImperativeHandle: Expose only necessary methods to parent components
When to Use Refs
Refs are ideal for:- Managing focus, text selection, or media playback
- Triggering imperative animations
- Integrating with third-party DOM libraries
- Storing mutable values that don’t trigger re-renders
- Anything that can be done declaratively
- Accessing child component state (use state lifting instead)
- Replacing props or state
See Also
- Hooks - Learn about
useRefanduseImperativeHandle - Component API - Component APIs and lifecycle