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 9, 2024
1 parent f7ac5e8 commit aedbb6d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/fix-merge-props.md
@@ -0,0 +1,5 @@
---
"@remix-run/react": patch
---

Fix the use of mergeRefs in `NavLink` and `Link` by using useCallback to avoid redundant ref calls.
1 change: 1 addition & 0 deletions contributors.yml
Expand Up @@ -291,6 +291,7 @@
- jmarbutt
- jmasson
- jmorel88
- jmurzy
- JNaftali
- jo-ninja
- joaosamouco
Expand Down
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 aedbb6d

Please sign in to comment.