useComposedRef
Keeps a ref to your own element while still forwarding it to whatever ref the parent passed in.
- Hook
- 1 examples
pnpm dlx shadcn@latest add https://hextaui.com/r/use-composed-ref.jsonAdds the hook and anything it depends on to your project.
Copy and paste the following code into your project.
hooks/use-composed-ref.ts Update the import paths to match your project setup.
In React 19, ref is a regular prop. When your component also needs the element for itself, you have two refs and only one ref attribute. This hook gives you an object ref to read, plus a callback that fills both refs.
This compiles, but the parent's ref is dropped, so ref.current stays null in the parent. With useComposedRef, both the parent and the component get the element.
- The returned
inputRefis a normalRefObject, so you can pass it to hooks that expect one, likeuseAutosizeoruseInvalidShake. setRefkeeps the same identity while the parent's ref does, so React doesn't detach and reattach it on every render.- Works with object refs, callback refs and no ref at all.
Use useComposedRef when you combine exactly one forwarded ref with your own object ref, which is most components. Use useMergedRef when you combine more than two, when one of them is a callback ref from another hook, or when a forwarded callback ref returns a React 19 cleanup function. useComposedRef calls a callback ref with null on detach instead of running its cleanup.
| Prop | Type | Default |
|---|---|---|
refThe ref your component received. | Ref<T> | undefined | – |
| Returns | Description |
|---|---|
[0] RefObject<T | null> | Your own ref to the element. |
[1] (node: T | null) => void | Pass to the element's ref. Fills both refs. |
Input, Textarea, NativeSelect, Field and InputGroup.
- FieldLabels, descriptions and errors wired to their control, with validation states and layouts for forms.
- InputA text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- Input groupAn input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- Native selectThe browser's own select, styled to match Input, with a quiet placeholder, Field support and the OS picker on every device.
- SidebarAn app sidebar that collapses to icons or off canvas, stays pinned under your header, and becomes a swipeable sheet on phones.
- TextareaMulti-line text that grows smoothly with what you write between a minimum and maximum number of rows, with counters, validation and a submit shortcut.