Skip to content

Instantly share code, notes, and snippets.

@carloitaben
Created December 9, 2024 21:26
Show Gist options
  • Select an option

  • Save carloitaben/996a6014cf978a7271532fce249ffc30 to your computer and use it in GitHub Desktop.

Select an option

Save carloitaben/996a6014cf978a7271532fce249ffc30 to your computer and use it in GitHub Desktop.
React 19 merge refs
import type { Ref } from "react"
function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): Ref<T> {
return (value) => {
const cleanups = refs.reduce<VoidFunction[]>((accumulator, ref) => {
if (typeof ref === "function") {
const cleanup = ref(value)
if (typeof cleanup === "function") {
accumulator.push(cleanup)
}
} else if (ref) {
ref.current = value
}
return accumulator
}, [])
return () => {
cleanups.forEach((cleanup) => cleanup())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment