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

perf(useMap): reduce re-render #2388

Closed
wants to merge 10 commits into from
44 changes: 44 additions & 0 deletions packages/hooks/src/useMap/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,28 @@ describe('useMap', () => {
]);
});

it('should not render if set same key-value pair', () => {
let count = 0;
const { result } = renderHook(() => {
count++;

return useMap([['hello', 'world']]);
});
const [, utils] = result.current;

expect(count).toBe(1);

act(() => {
utils.set('hello', 'world');
});
expect(count).toBe(1);

act(() => {
utils.set('hello', 'ahooks');
});
expect(count).toBe(2);
});

it('should override current value if setting existing key', () => {
const { result } = setup([
['foo', 'bar'],
Expand Down Expand Up @@ -169,6 +191,28 @@ describe('useMap', () => {
]);
});

it('should not render if remove non-existing key', () => {
let count = 0;
const { result } = renderHook(() => {
count++;

return useMap([['hello', 'world']]);
});
const [, utils] = result.current;

expect(count).toBe(1);

act(() => {
utils.remove('hi');
});
expect(count).toBe(1);

act(() => {
utils.remove('hello');
});
expect(count).toBe(2);
});

it('reset should be work', () => {
const { result } = setup([['msg', 'hello']]);
const { set, reset } = result.current[1];
Expand Down
6 changes: 6 additions & 0 deletions packages/hooks/src/useMap/index.ts
coding-ice marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ function useMap<K, T>(initialValue?: Iterable<readonly [K, T]>) {
const [map, setMap] = useState<Map<K, T>>(getInitValue);

const set = (key: K, entry: T) => {
if (map.has(key) && map.get(key) === entry) {
return;
}
setMap((prev) => {
const temp = new Map(prev);
temp.set(key, entry);
Expand All @@ -18,6 +21,9 @@ function useMap<K, T>(initialValue?: Iterable<readonly [K, T]>) {
};

const remove = (key: K) => {
if (!map.has(key)) {
return;
}
setMap((prev) => {
const temp = new Map(prev);
temp.delete(key);
Expand Down
Loading