setRef (lib/compose-refs.ts)

vobase · packages/template/src/lib/compose-refs.ts · typescript · MIT
ui

React ref utilities (setRef, composeRefs, useComposedRefs) handling callback and object refs with React 19 cleanup support.

// Source: https://github.com/vobase/vobase | License: MIT | Copyright 2026 Vobase
// Provided via justclaw.it.com; keep this notice with the code.
import * as React from 'react'

type PossibleRef<T> = React.Ref<T> | undefined

/**
 * Set a given ref to a given value
 * This utility takes care of different types of refs: callback refs and RefObject(s)
 */
function setRef<T>(ref: PossibleRef<T>, value: T) {
  if (typeof ref === 'function') {
    return ref(value)
  }

  if (ref !== null && ref !== undefined) {
    ref.current = value
  }
}

/**
 * A utility to compose multiple refs together
 * Accepts callback refs and RefObject(s)
 */
function composeRefs<T>(...refs: PossibleRef<T>[]): React.RefCallback<T> {
  return (node) => {
    let hasCleanup = false
    const cleanups = refs.map((ref

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key