Skip to main content
Refs provide a way to access DOM nodes or Preact elements created in the render method. They’re also useful for storing mutable values that persist across renders without causing re-renders.

When to Use Refs

Refs are useful for:
  • Managing focus, text selection, or media playback
  • Triggering imperative animations
  • Integrating with third-party DOM libraries
  • Storing values that don’t affect rendering
Don’t overuse refs. Most things should be done declaratively with props and state.

Creating Refs

Preact provides two ways to create refs:

Accessing DOM Elements

The most common use of refs is to access DOM elements directly:

Callback Refs

Instead of passing a ref object, you can pass a function. Preact will call it with the DOM element:
Callback refs are called with null when the component unmounts. Always check if the element exists.

Storing Mutable Values

Refs aren’t just for DOM elements. They’re perfect for storing values that need to persist across renders but shouldn’t trigger re-renders when changed:

Forwarding Refs

Sometimes you need to pass a ref through a component to one of its children. Use forwardRef from preact/compat:

Ref Best Practices

Common Patterns

Next Steps

Hooks

Learn about useRef and other hooks in depth

Fragments

Return multiple elements without wrapper nodes