Skip to content
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: useComposeRef memo logic #458

Merged
merged 1 commit into from
Aug 8, 2023
Merged
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
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
Loading