Skip to content

Commit 25fd32b

Browse files
authored
fix: useComposeRef memo logic (#458)
1 parent 4fd907f commit 25fd32b

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
export { default as useEvent } from './hooks/useEvent';
12
export { default as useMergedState } from './hooks/useMergedState';
3+
export { useComposeRef } from './ref';
24
export { default as get } from './utils/get';
35
export { default as set } from './utils/set';
46
export { default as warning } from './warning';

src/ref.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export function useComposeRef<T>(...refs: React.Ref<T>[]): React.Ref<T> {
3232
() => composeRef(...refs),
3333
refs,
3434
(prev, next) =>
35-
prev.length === next.length && prev.every((ref, i) => ref === next[i]),
35+
prev.length !== next.length || prev.every((ref, i) => ref !== next[i]),
3636
);
3737
}
3838

tests/ref.test.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* eslint-disable no-eval */
2+
import { fireEvent, render } from '@testing-library/react';
23
import React from 'react';
3-
import { render } from '@testing-library/react';
4+
import useEvent from '../src/hooks/useEvent';
45
import { composeRef, supportRef, useComposeRef } from '../src/ref';
56

67
describe('ref', () => {
@@ -35,6 +36,37 @@ describe('ref', () => {
3536
expect(ref1.current).toBeTruthy();
3637
expect(ref1.current).toBe(ref2.current);
3738
});
39+
40+
it('useComposeRef not changed', () => {
41+
let count = 0;
42+
43+
const Demo = () => {
44+
const [, forceUpdate] = React.useState({});
45+
46+
const ref1 = React.useRef();
47+
const ref2 = React.useRef();
48+
const refFn = useEvent(() => {
49+
count += 1;
50+
});
51+
const mergedRef = useComposeRef(ref1, ref2, refFn);
52+
return (
53+
<button ref={mergedRef} onClick={() => forceUpdate({})}>
54+
Update
55+
</button>
56+
);
57+
};
58+
59+
const { container, unmount } = render(<Demo />);
60+
expect(count).toEqual(1);
61+
62+
for (let i = 0; i < 10; i += 1) {
63+
fireEvent.click(container.querySelector('button'));
64+
expect(count).toEqual(1);
65+
}
66+
67+
unmount();
68+
expect(count).toEqual(2);
69+
});
3870
});
3971

4072
describe('supportRef', () => {

0 commit comments

Comments
 (0)