Signature
Type Parameters
any
default:"any"
The type of the value the ref will hold (e.g.,
HTMLDivElement, HTMLInputElement).Return Value
Returns aRefObject<T> with the following structure:
current property:
- Initially set to
null - Updated by Preact when the component mounts
- Set to the DOM node or component instance
- Reset to
nullwhen the component unmounts
Description
createRef creates a mutable object whose current property is initialized to null. This object persists for the lifetime of the component and is used to access DOM nodes or component instances directly.
Refs are useful for:
- Managing focus, text selection, or media playback
- Triggering imperative animations
- Integrating with third-party DOM libraries
- Accessing component methods
Implementation
The function is implemented insrc/create-element.js:73:
current property initialized to null.
Usage Examples
Accessing DOM Elements
With Function Components
Measuring DOM Elements
Managing Focus
With TypeScript
Text Selection
Integrating Third-Party Libraries
Multiple Refs
Forwarding Refs
Ref vs useRef Hook
For function components, prefer theuseRef hook:
createRefcreates a new object every timeuseRefpersists the same object across re-rendersuseRefis preferred for function components
Common Patterns
Conditional Refs
Callback Refs
For more control, use callback refs instead:Best Practices
- Check for null: Always check if
ref.currentexists before using it
- Don’t overuse refs: Use refs only when necessary. For most cases, data flow through props is preferred
- Avoid string refs: Preact supports string refs for compatibility, but object refs are preferred
- Function components: Use
useRefhook instead ofcreateRefin function components