Skip to main content
Creates a mutable ref object that can hold a reference to a DOM node or component instance.

Signature

Type Parameters

any
default:"any"
The type of the value the ref will hold (e.g., HTMLDivElement, HTMLInputElement).

Return Value

Returns a RefObject<T> with the following structure:
The current property:
  • Initially set to null
  • Updated by Preact when the component mounts
  • Set to the DOM node or component instance
  • Reset to null when 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 in src/create-element.js:73:
The implementation is simple - it returns a plain object with a 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 the useRef hook:
Key differences:
  • createRef creates a new object every time
  • useRef persists the same object across re-renders
  • useRef is preferred for function components

Common Patterns

Conditional Refs

Callback Refs

For more control, use callback refs instead:

Best Practices

  1. Check for null: Always check if ref.current exists before using it
  1. Don’t overuse refs: Use refs only when necessary. For most cases, data flow through props is preferred
  2. Avoid string refs: Preact supports string refs for compatibility, but object refs are preferred
  1. Function components: Use useRef hook instead of createRef in function components
  • useRef hook - Ref hook for function components
  • forwardRef - Forward refs through components
  • Component - Class component API
  • h - Create elements with refs