Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes the use of mergeRefs in the NavLink and Link #9021

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-merge-props.md
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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);
}