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
Creating Refs
Preact provides two ways to create refs:- useRef Hook (Recommended)
- createRef
The It returns an object with a
useRef hook is the recommended way to create refs in function components:How useRef Works
TheuseRef hook is implemented in hooks/src/index.js as a simple wrapper around useMemo:current property that persists across renders.Reference: hooks/src/index.js:306-309Accessing 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. UseforwardRef 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