Skip to content

fix: merged ref behavior in react 19 #102

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

Open
wants to merge 1 commit into
base: master
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 35 additions & 12 deletions src/useMergedRefs.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,42 @@
import { useMemo } from 'react'
import { RefCallback, useMemo, version } from 'react'

const isReact19 = parseInt(version.split('.')[0]!, 10) >= 19

type CallbackRef<T> = (ref: T | null) => void
type Ref<T> = React.MutableRefObject<T> | CallbackRef<T>

function toFnRef<T>(ref?: Ref<T> | null) {
return !ref || typeof ref === 'function'
? ref
: (value: T | null) => {
ref.current = value as T
}
if (!ref || typeof ref === 'function') {
return ref
}

return (value: T | null) => {
ref.current = value as T
}
}

function cleanUp<T>(cleanup: unknown, ref: RefCallback<T> | null | undefined) {
if (typeof cleanup === 'function') {
cleanup()
} else if (ref) {
ref(null)
}
}

export function mergeRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null) {
const a = toFnRef(refA)
const b = toFnRef(refB)
return (value: T | null) => {
if (a) a(value)
if (b) b(value)
const refASetter = toFnRef(refA)
const refBSetter = toFnRef(refB)

if (isReact19) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need a react 19 check? Could it return the cleanup function regardless of version, which would be ignored in R18 and actually work in R19?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know. I think there are react warnings if you return stuff

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah ok - in that case, this code is missing the return handler for anything below R19

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ya but that is the same as now right? no return for < 19

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I meant the mergeRefs function. mergeRefs currently doesn't return a function on R18 and below

You meant to do this right?

export function mergeRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null) {
  const refASetter = toFnRef(refA);
  const refBSetter = toFnRef(refB);

  return (value: T | null) => {
    const cleanupA = refASetter?.(value);
    const cleanupB = refBSetter?.(value);

    if (isReact19) {  // <--- This moved inside
      return () => {
        cleanUp(cleanupA, refASetter);
        cleanUp(cleanupB, refBSetter);
      };
    }
  };
}

return (value: T | null) => {
const cleanupA = refASetter?.(value)
const cleanupB = refBSetter?.(value)

return () => {
cleanUp(cleanupA, refASetter)
cleanUp(cleanupB, refBSetter)
}
}
}
}

Expand All @@ -36,7 +56,10 @@ export function mergeRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null) {
* @param refB A Callback or mutable Ref
* @category refs
*/
function useMergedRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null) {
function useMergedRefs<T>(
refA?: Ref<T | null> | null,
refB?: Ref<T | null> | null,
) {
return useMemo(() => mergeRefs(refA, refB), [refA, refB])
}

Expand Down
73 changes: 72 additions & 1 deletion test/useMergedRefs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import useMergedRefs from '../src/useMergedRefs.js'
import { render } from '@testing-library/react'

describe('useMergedRefs', () => {
it('should return a function that returns mount state', () => {
it('should work with forwardRef', () => {
let innerRef: HTMLButtonElement
const outerRef = React.createRef<HTMLButtonElement>()

Expand All @@ -18,9 +18,80 @@ describe('useMergedRefs', () => {
return <button ref={mergedRef} {...props} />
})

render(<Button ref={outerRef} />)

expect(innerRef!.tagName).toEqual('BUTTON')
expect(outerRef.current!.tagName).toEqual('BUTTON')
})

it('should work with plain function component', () => {
let innerRef: HTMLButtonElement
const outerRef = React.createRef<HTMLButtonElement>()

const Button = ({ ref }: { ref: React.Ref<HTMLButtonElement> }) => {
const [buttonEl, attachRef] = useCallbackRef<HTMLButtonElement>()
innerRef = buttonEl!

const mergedRef = useMergedRefs(ref, attachRef)

return <button ref={mergedRef} />
}

render(<Button ref={outerRef} />)

expect(innerRef!.tagName).toEqual('BUTTON')
expect(outerRef.current!.tagName).toEqual('BUTTON')
})

it('should call refs with null when unmounting', () => {
let innerRef: HTMLButtonElement | null = null

const outerRef = React.createRef<HTMLButtonElement>()

function Button({ ref }: { ref: React.Ref<HTMLButtonElement> }) {
const mergedRef = useMergedRefs(ref, (value) => {
innerRef = value
})

return <button ref={mergedRef} />
}

const result = render(<Button ref={outerRef} />)

expect(innerRef!.tagName).toEqual('BUTTON')
expect(outerRef.current!.tagName).toEqual('BUTTON')

result.unmount()

expect(innerRef).toBeNull()
expect(outerRef.current).toBeNull()
})

it('should call refs cleanup functions', () => {
let innerRef: HTMLButtonElement | null = null

const outerRef = React.createRef<HTMLButtonElement>()

function Button({ ref }: { ref: React.Ref<HTMLButtonElement> }) {
const mergedRef = useMergedRefs(ref, (value) => {
innerRef = value

return () => {
innerRef = 'hi' as any
}
})

return <button ref={mergedRef} />
}

const result = render(<Button ref={outerRef} />)

expect(innerRef!.tagName).toEqual('BUTTON')
expect(outerRef.current!.tagName).toEqual('BUTTON')

result.unmount()

expect(innerRef).toEqual('hi')
expect(outerRef.current).toBeNull()
})
})