Skip to content

Commit

Permalink
fix: useComposeRef memo logic (#458)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ authored Aug 8, 2023
1 parent 4fd907f commit 25fd32b
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export { default as useEvent } from './hooks/useEvent';
export { default as useMergedState } from './hooks/useMergedState';
export { useComposeRef } from './ref';
export { default as get } from './utils/get';
export { default as set } from './utils/set';
export { default as warning } from './warning';
2 changes: 1 addition & 1 deletion src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function useComposeRef<T>(...refs: React.Ref<T>[]): React.Ref<T> {
() => composeRef(...refs),
refs,
(prev, next) =>
prev.length === next.length && prev.every((ref, i) => ref === next[i]),
prev.length !== next.length || prev.every((ref, i) => ref !== next[i]),
);
}

Expand Down
34 changes: 33 additions & 1 deletion tests/ref.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable no-eval */
import { fireEvent, render } from '@testing-library/react';
import React from 'react';
import { render } from '@testing-library/react';
import useEvent from '../src/hooks/useEvent';
import { composeRef, supportRef, useComposeRef } from '../src/ref';

describe('ref', () => {
Expand Down Expand Up @@ -35,6 +36,37 @@ describe('ref', () => {
expect(ref1.current).toBeTruthy();
expect(ref1.current).toBe(ref2.current);
});

it('useComposeRef not changed', () => {
let count = 0;

const Demo = () => {
const [, forceUpdate] = React.useState({});

const ref1 = React.useRef();
const ref2 = React.useRef();
const refFn = useEvent(() => {
count += 1;
});
const mergedRef = useComposeRef(ref1, ref2, refFn);
return (
<button ref={mergedRef} onClick={() => forceUpdate({})}>
Update
</button>
);
};

const { container, unmount } = render(<Demo />);
expect(count).toEqual(1);

for (let i = 0; i < 10; i += 1) {
fireEvent.click(container.querySelector('button'));
expect(count).toEqual(1);
}

unmount();
expect(count).toEqual(2);
});
});

describe('supportRef', () => {
Expand Down

1 comment on commit 25fd32b

@vercel
Copy link

@vercel vercel bot commented on 25fd32b Aug 8, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

util – ./

util.vercel.app
util-git-master-react-component.vercel.app
util-react-component.vercel.app

Please sign in to comment.