File size: 2,047 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'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]
  )
}