Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Created June 11, 2025 08:37
Show Gist options
  • Save Phryxia/0a5356def013135dba4c5af54465c656 to your computer and use it in GitHub Desktop.
Save Phryxia/0a5356def013135dba4c5af54465c656 to your computer and use it in GitHub Desktop.
TypeScript implementation of react `ref` merge for `HTMLElement`
export function useRefMerge<T>(...refs: (RefCallback<T> | MutableRefObject<T | null> | ForwardedRef<T>)[]) {
const assignedObject = useRef<T>()
return useCallback((node: T) => {
assignedObject.current = node
for (const ref of refs) {
if (typeof ref === 'function') {
ref(node)
} else if (typeof ref === 'object' && ref) {
ref.current = node
}
}
}, refs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment