Skip to content

Commit

Permalink
Fixes the use of mergeRefs in the NavLink and Link
Browse files Browse the repository at this point in the history
useCallback is necessary to prevent multiple calls to refs on each render.
  • Loading branch information
jmurzy committed Mar 8, 2024
1 parent f7ac5e8 commit 8b477c3
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/remix-react/components.tsx
Expand Up @@ -202,12 +202,14 @@ let NavLink = React.forwardRef<HTMLAnchorElement, RemixNavLinkProps>(
props
);

let mergedRef = useMergedRef(forwardedRef, ref)

return (
<>
<RouterNavLink
{...props}
{...prefetchHandlers}
ref={mergeRefs(forwardedRef, ref)}
ref={mergedRef}
to={to}
/>
{shouldPrefetch && !isAbsolute ? (
Expand Down Expand Up @@ -236,12 +238,14 @@ let Link = React.forwardRef<HTMLAnchorElement, RemixLinkProps>(
props
);

let mergedRef = useMergedRef(forwardedRef, ref)

return (
<>
<RouterLink
{...props}
{...prefetchHandlers}
ref={mergeRefs(forwardedRef, ref)}
ref={mergedRef}
to={to}
/>
{shouldPrefetch && !isAbsolute ? (
Expand Down Expand Up @@ -1213,3 +1217,12 @@ function mergeRefs<T = any>(
});
};
}

function useMergedRef<T = any>(
...refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>
): React.RefCallback<T> {
let rs = refs.filter((r): r is React.Ref<T> => !!r);

// eslint-disable-next-line react-hooks/exhaustive-deps
return React.useCallback(mergeRefs(...rs), rs);
}

0 comments on commit 8b477c3

Please sign in to comment.