Skip to content

useAugmentedRef breaks the measure function (and possibly a few others). #110

@Choco-milk-for-u

Description

@Choco-milk-for-u

Passing ref in components like hover-card`s Trigger component doesn’t return the measure function (it’s undefined) on mobile.
the reason is useAugmentedRef spreads augmentedRef:

return {
  ...augmentedRef.current, // <---- this
  ...methods,
};

in

export function useAugmentedRef<T>({
  ref,
  methods,
  deps = [],
}: AugmentRefProps<T>) {
  const augmentedRef = React.useRef<T>(null);
  React.useImperativeHandle(
    ref,
    () => {
      if (typeof augmentedRef === 'function' || !augmentedRef?.current) {
        return {} as T;
      }
      return {
        ...augmentedRef.current,
        ...methods,
      };
    },
    deps
  );
  return augmentedRef;
}

if you use wrapper functions instead of spreading for example, writing measure fun by hand it will work.

return {
  ...augmentedRef.current,
measure:(args)=>augmentedRef.current.measure(args),
  ...methods,
};

solutions that DO work:

Mutate ref for custom methods that useAugmentedRef was created for (like open or close methods in hover-card's Trigger component) directly in the ref callback of react native components.
Something like that:

 ref={(nativeRef) => {
        if (!nativeRef) return;
        nativeRef.open = () => {
          onOpenChange(true);
          ref.current?.measure((_x, _y, width, height, pageX, pageY) => {
            setTriggerPosition({ width, pageX, pageY, height });
          });
        };
        nativeRef.close = () => {
          setTriggerPosition(null);
          onOpenChange(false);
        }
        ref.current = nativeRef;
      }}

useAugmentedRef will have to be removed almost in each file.

Or use anything BUT useImperativeHandle (useLayoutEffect), or adding a deps array with a custom variable that is unique to each component (like open / close state in hover-card's Trigger component) in useImperativeHandle . (bad workaround)

Since my methods might be wrong, or I might be wrong on the whole situation, I opened an issue. If its okay, I would like to make a PR with one of my solutions thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions