Skip to content
Design From Labs
UtilityfoundationsLabs examplesMIT

composeRefs

Combines several React refs (callbacks or objects) into one ref callback, with React 19 cleanup support.

Install

Item compose-refs · registry JSON

npx shadcn@latest add https://labs.designfrom.com/r/compose-refs.json

Source

Comments are kept. The header lists provenance, license and install commands for people and coding assistants.

lib/compose-refs.ts
import type * as React from "react";

/**
 * @dfl-header: v1, generated by labs.designfrom.com at build time
 * Item: compose-refs (composeRefs)
 * What: Combines several React refs (callbacks or objects) into one ref
 *    callback, with React 19 cleanup support.
 * Status: ready. License: MIT. Author: Design From Labs
 *    <https://labs.designfrom.com>
 * Source: https://github.com/Design-from-labs/labs @ 803b92c1a30e (examples/compose-refs)
 * Credits: S-003 React (MIT); S-004 shadcn/ui and its registry schema (MIT)
 * Install: npx shadcn@latest add https://labs.designfrom.com/r/compose-refs.json
 *   npx shadcn@latest add @designfrom/compose-refs
 *   npm i @designfrom/react, then import { composeRefs } from "@designfrom/react/compose-refs";
 * Docs: https://labs.designfrom.com/ui/compose-refs (index: https://labs.designfrom.com/llms.txt)
 */

/**
 * One ref callback that keeps every given ref pointing at the same element.
 * Works with callback refs and ref objects, and returns a React 19 cleanup
 * that releases each of them.
 */
export function composeRefs<T>(
  ...refs: Array<React.Ref<T> | undefined>
): React.RefCallback<T> {
  return (node) => {
    const cleanups: Array<() => void> = [];
    for (const ref of refs) {
      if (typeof ref === "function") {
        const cleanup = ref(node);
        cleanups.push(
          typeof cleanup === "function" ? cleanup : () => ref(null),
        );
      } else if (ref) {
        ref.current = node;
        cleanups.push(() => {
          ref.current = null;
        });
      }
    }
    return () => {
      for (const cleanup of cleanups) {
        cleanup();
      }
    };
  };
}

Dependencies

  • None.

Usage

<div ref={composeRefs(localRef, forwardedRef)} />

Props

PropTypeDefaultDescription
...refsArray<React.Ref<T> | undefined>The refs to keep in sync with one element.

Credits

License and source

License
MIT
Author
Design From Labs <https://labs.designfrom.com>
Source
github.com/Design-from-labs/labs
Commit
803b92c1a30e
Date
2026-10-12
Origin
labs-examples