All files / hooks/use-disclosure/src utils.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 4/4
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                          56x   56x 56x     56x   26x 13x        
import { useEffect, useMemo, useRef } from "react";
 
/**
 * Returns a stable function that always invokes the *latest* `callback`.
 *
 * Lets the disclosure handlers keep a permanent identity (safe as props / effect
 * deps) while still calling the freshest `onOpen` / `onClose` the consumer
 * passed. The stored ref is updated in an effect (not during render), keeping it
 * concurrent-mode / StrictMode safe.
 */
export function useCallbackRef<Args extends unknown[], Return>(
  callback: ((...args: Args) => Return) | undefined
): (...args: Args) => Return | undefined {
  const callbackRef = useRef(callback);
 
  useEffect(() => {
    callbackRef.current = callback;
  });
 
  return useMemo(
    () =>
      (...args: Args) =>
        callbackRef.current?.(...args),
    []
  );
}