New: Activity Terrain +12 more

useMergedRef

Combines any number of callback and object refs into one, with React 19 ref cleanup for each of them.

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-merged-ref.json
Install manually
  1. Copy this into hooks/use-merged-ref.ts:

    use-merged-ref.ts
    import * as React from "react"
    
    function assignRef<T>(ref: React.Ref<T> | undefined, node: T | null) {
      if (typeof ref === "function") {
        const cleanup = ref(node)
        return typeof cleanup === "function" ? cleanup : () => ref(null)
      }
      if (ref) {
        ref.current = node
        return () => {
          ref.current = null
        }
      }
      return undefined
    }
    
    function useMergedRef<T>(...refs: Array<React.Ref<T> | undefined>) {
      return React.useCallback((node: T | null) => {
        const cleanups = refs.map((ref) => assignRef(ref, node))
        return () => {
          for (const cleanup of cleanups) {
            cleanup?.()
          }
        }
      }, refs)
    }
    
    export { useMergedRef }

Feedback

Questions, bugs or ideas for useMergedRef? Post them here, or reply to someone else. Sign in with GitHub to comment.