useComposedRef
Keeps a ref to your own element while still forwarding it to whatever ref the parent passed in.
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.