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 Apr 19, 2024
1 parent 7aecb30 commit c2bfaa0
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 @@ -292,6 +292,7 @@
- jmarbutt
- jmasson
- jmorel88
- jmurzy
- JNaftali
- jo-ninja
- joaosamouco
Expand Down
17 changes: 15 additions & 2 deletions packages/remix-react/components.tsx
Expand Up @@ -203,12 +203,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 @@ -237,12 +239,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 @@ -1270,3 +1274,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 c2bfaa0

Please sign in to comment.