-
Notifications
You must be signed in to change notification settings - Fork 27.8k
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
fix: be more defensive in useMergedRef #75088
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
import { useMemo, useRef, type Ref } from 'react' | ||
import { useCallback, useRef, type Ref } from 'react' | ||
|
||
// This is a compatibility hook to support React 18 and 19 refs. | ||
// In 19, a cleanup function from refs may be returned. | ||
|
@@ -11,24 +11,40 @@ export function useMergedRef<TElement>( | |
refA: Ref<TElement>, | ||
refB: Ref<TElement> | ||
): Ref<TElement> { | ||
const cleanupA = useRef<() => void>(() => {}) | ||
const cleanupB = useRef<() => void>(() => {}) | ||
const cleanupA = useRef<(() => void) | null>(null) | ||
const cleanupB = useRef<(() => void) | null>(null) | ||
|
||
return useMemo(() => { | ||
if (!refA || !refB) { | ||
return refA || refB | ||
} | ||
Comment on lines
-17
to
-19
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the removal of this fast path is the real change here -- this is what was causing us to return |
||
|
||
return (current: TElement | null): void => { | ||
// NOTE: In theory, we could skip the wrapping if only one of the refs is non-null. | ||
// (this happens often if the user doesn't pass a ref to Link/Form/Image) | ||
// But this can cause us to leak a cleanup-ref into user code (e.g. via `<Link legacyBehavior>`), | ||
// and the user might pass that ref into ref-merging library that doesn't support cleanup refs | ||
// (because it hasn't been updated for React 19) | ||
// which can then cause things to blow up, because a cleanup-returning ref gets called with `null`. | ||
// So in practice, it's safer to be defensive and always wrap the ref, even on React 19. | ||
return useCallback( | ||
(current: TElement | null): void => { | ||
if (current === null) { | ||
cleanupA.current() | ||
cleanupB.current() | ||
const cleanupFnA = cleanupA.current | ||
if (cleanupFnA) { | ||
cleanupA.current = null | ||
cleanupFnA() | ||
} | ||
const cleanupFnB = cleanupB.current | ||
if (cleanupFnB) { | ||
cleanupB.current = null | ||
cleanupFnB() | ||
} | ||
} else { | ||
cleanupA.current = applyRef(refA, current) | ||
cleanupB.current = applyRef(refB, current) | ||
if (refA) { | ||
cleanupA.current = applyRef(refA, current) | ||
} | ||
if (refB) { | ||
cleanupB.current = applyRef(refB, current) | ||
} | ||
} | ||
} | ||
}, [refA, refB]) | ||
}, | ||
[refA, refB] | ||
) | ||
} | ||
|
||
function applyRef<TElement>( | ||
|
13 changes: 13 additions & 0 deletions
13
test/production/next-link-legacybehavior-ref-merging/app/layout.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import * as React from 'react' | ||
|
||
export default function RootLayout({ | ||
children, | ||
}: { | ||
children: React.ReactNode | ||
}) { | ||
return ( | ||
<html lang="en"> | ||
<body>{children}</body> | ||
</html> | ||
) | ||
} |
11 changes: 11 additions & 0 deletions
11
test/production/next-link-legacybehavior-ref-merging/app/link-target/page.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import * as React from 'react' | ||
import Link from 'next/link' | ||
|
||
export default function Page() { | ||
return ( | ||
<> | ||
<h1>Navigation worked!</h1> | ||
<Link href="/">Go back</Link> | ||
</> | ||
) | ||
} |
87 changes: 87 additions & 0 deletions
87
test/production/next-link-legacybehavior-ref-merging/app/page.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
'use client' | ||
import Link from 'next/link' | ||
import * as React from 'react' | ||
import { | ||
useCallback, | ||
useState, | ||
type RefCallback, | ||
type Ref, | ||
type ComponentPropsWithRef, | ||
type ReactNode, | ||
} from 'react' | ||
|
||
export default function Page() { | ||
return ( | ||
<> | ||
<h1>Home</h1> | ||
<ToggleVisibility> | ||
<Link href="/link-target" legacyBehavior> | ||
<AnchorThatDoesRefMerging id="test-link"> | ||
Go to /link-target | ||
</AnchorThatDoesRefMerging> | ||
</Link> | ||
</ToggleVisibility> | ||
</> | ||
) | ||
} | ||
|
||
function ToggleVisibility({ children }: { children: ReactNode }) { | ||
const [isVisible, setIsVisible] = useState(true) | ||
return ( | ||
<> | ||
<div> | ||
<button type="button" onClick={() => setIsVisible((prev) => !prev)}> | ||
{isVisible ? 'Hide content' : 'Show content'} | ||
</button> | ||
</div> | ||
{isVisible ? children : null} | ||
</> | ||
) | ||
} | ||
|
||
function AnchorThatDoesRefMerging({ | ||
ref, | ||
children, | ||
...anchorProps | ||
}: ComponentPropsWithRef<'a'>) { | ||
const customRef: RefCallback<HTMLAnchorElement> = useCallback((el) => { | ||
if (el) { | ||
console.log('hello friends i am here') | ||
} else { | ||
console.log('goodbye friends i am gone') | ||
} | ||
}, []) | ||
|
||
const finalRef = useBuggyRefMerge(customRef, ref ?? null) | ||
return ( | ||
<a ref={finalRef} {...anchorProps}> | ||
{children} | ||
</a> | ||
) | ||
} | ||
|
||
/** A ref-merging function that doesn't account for cleanup refs (added in React 19) | ||
* https://react.dev/blog/2024/12/05/react-19#cleanup-functions-for-refs | ||
*/ | ||
function useBuggyRefMerge<TElement>( | ||
refA: Ref<TElement>, | ||
refB: Ref<TElement> | ||
): RefCallback<TElement> { | ||
return useCallback( | ||
(current: TElement | null) => { | ||
for (const ref of [refA, refB]) { | ||
if (!ref) { | ||
continue | ||
} | ||
if (typeof ref === 'object') { | ||
ref.current = current | ||
} else { | ||
// BUG!!! | ||
// This would work in 18, but in 19 it can return a cleanup which will get swallowed here | ||
ref(current) | ||
} | ||
} | ||
}, | ||
[refA, refB] | ||
) | ||
} |
25 changes: 25 additions & 0 deletions
25
test/production/next-link-legacybehavior-ref-merging/index.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { nextTestSetup } from 'e2e-utils' | ||
|
||
// NOTE: this test is checking for a bug in prefetching code, | ||
// so we only enable it in production | ||
|
||
describe('Link with legacyBehavior - handles buggy userspace ref merging', () => { | ||
const { next } = nextTestSetup({ | ||
files: __dirname, | ||
}) | ||
it('does not crash when Link unmounts', async () => { | ||
const browser = await next.browser('/') | ||
expect(await browser.elementByCss('h1').text()).toEqual('Home') | ||
expect(await browser.hasElementByCssSelector('#test-link')).toBe(true) | ||
|
||
// hide the link, unmounting it | ||
await browser.elementByCss('button').click() | ||
expect(await browser.hasElementByCssSelector('#test-link')).toBe(false) | ||
|
||
// shouldn't cause a crash | ||
expect(await browser.elementByCss('h1').text()).toEqual('Home') | ||
expect(await browser.elementByCss('body').text()).not.toContain( | ||
'Application error: a client-side exception has occurred (see the browser console for more information).' | ||
) | ||
}) | ||
}) |
2 changes: 2 additions & 0 deletions
2
test/production/next-link-legacybehavior-ref-merging/next.config.mjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
/** @type {import('next').NextConfig} */ | ||
export default {} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
unrelated to the issue, just a drive-by fix