Skip to content
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
12 changes: 9 additions & 3 deletions src/Immutable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ export function makeImmutable<T extends React.ComponentType<any>>(Component: T):
* Wrapped Component with `React.memo`.
* But will rerender when parent with `makeImmutable` rerender.
*/
export function responseImmutable<T extends React.ComponentType<any>>(Component: T): T {
export function responseImmutable<T extends React.ComponentType<any>>(
Component: T,
propsAreEqual?: (
prevProps: Readonly<React.ComponentProps<T>>,
nextProps: Readonly<React.ComponentProps<T>>,
) => boolean,
): T {
const refAble = supportRef(Component);

const ImmutableComponent = function (props: any, ref: any) {
Expand All @@ -51,6 +57,6 @@ export function responseImmutable<T extends React.ComponentType<any>>(Component:
}

return refAble
? React.memo(React.forwardRef(ImmutableComponent))
: (React.memo(ImmutableComponent) as any);
? React.memo(React.forwardRef(ImmutableComponent), propsAreEqual)
: (React.memo(ImmutableComponent, propsAreEqual) as any);
}
23 changes: 23 additions & 0 deletions tests/immutable.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,27 @@ describe('Immutable', () => {
expect(rootRef.current).toBe(container.querySelector('.root'));
expect(rawRef.current).toBe(container.querySelector('.raw'));
});

it('customize propsAreEqual', () => {
const Input: React.FC<{
value: string;
onChange: React.ChangeEventHandler<HTMLInputElement>;
}> = props => (
<>
<input {...props} />
<RenderTimer id="input" />
</>
);

const ImmutableInput = responseImmutable(Input, (prev, next) => prev.value === next.value);

const { container, rerender } = render(<ImmutableInput value="same" onChange={() => {}} />);
expect(container.querySelector('#input').textContent).toEqual('1');

rerender(<ImmutableInput value="same" onChange={() => {}} />);
expect(container.querySelector('#input').textContent).toEqual('1');

rerender(<ImmutableInput value="not-same" onChange={() => {}} />);
expect(container.querySelector('#input').textContent).toEqual('2');
});
});