useComposedRef
Keeps a ref to your own element while still forwarding it to whatever ref the parent passed in.
1 exampleFrom HextaUI (MIT)
Installation
Run this in your project. It adds the files, installs the npm packages and anything this builds on, and sets up the theme:
npx shadcn@latest add https://kryptonite-ui.vercel.app/r/use-composed-ref.jsonInstall manually
Copy this into
hooks/use-composed-ref.ts:use-composed-ref.tsimport * as React from "react" function useComposedRef<T>(ref: React.Ref<T> | undefined) { const inner = React.useRef<T | null>(null) const setRef = React.useCallback( (node: T | null) => { inner.current = node if (typeof ref === "function") { ref(node) } else if (ref) { ref.current = node } }, [ref] ) return [inner, setRef] as const } export { useComposedRef }
Feedback
Questions, bugs or ideas for useComposedRef? Post them here, or reply to someone else. Sign in with GitHub to comment.