Skip to content
Open
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
46 changes: 46 additions & 0 deletions src/useMap/index.dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,50 @@ describe('useMap', () => {

spy.mockRestore();
});

it.each([0, Number.NaN, undefined, {count: 0}])('does not rerender when setting the same value %s', async (value) => {
let renders = 0;
const {result} = await renderHook(() => [++renders, useMap<string, unknown>([['key', value]])] as const);
const [, map] = expectResultValue(result);

await act(async () => {
expect(map.set('key', value)).toBe(map);
});

expect(expectResultValue(result)[0]).toBe(1);
expect(map.has('key')).toBe(true);
expect(map.get('key')).toBe(value);
});

it.each([
[0, 1],
[0, -0],
[-0, 0],
[{count: 0}, {count: 0}],
])('rerenders when changing a value from %s to %s', async (before, after) => {
let renders = 0;
const {result} = await renderHook(() => [++renders, useMap<string, unknown>([['key', before]])] as const);
const [, map] = expectResultValue(result);

await act(async () => {
expect(map.set('key', after)).toBe(map);
});

expect(expectResultValue(result)[0]).toBe(2);
expect(map.get('key')).toBe(after);
});

it('inserts a missing key with an undefined value and rerenders', async () => {
let renders = 0;
const {result} = await renderHook(() => [++renders, useMap<string, undefined>()] as const);
const [, map] = expectResultValue(result);

await act(async () => {
expect(map.set('key', undefined)).toBe(map);
});

expect(expectResultValue(result)[0]).toBe(2);
expect(map.has('key')).toBe(true);
expect(map.size).toBe(1);
});
});
9 changes: 8 additions & 1 deletion src/useMap/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ const proto = Map.prototype;
/**
* Tracks the state of a `Map`.
*
* `set` rerenders when adding a key or changing its value (compared with `Object.is`).
* Replace object values rather than mutating and setting the same reference.
*
* @param entries Initial entries iterator for underlying `Map` constructor.
*/

Expand All @@ -19,8 +22,12 @@ export function useMap<K = any, V = any>(entries?: ReadonlyArray<readonly [K, V]
mapRef.current = map;

map.set = (...args) => {
const [key, value] = args;
const changed = !map.has(key) || !Object.is(map.get(key), value);
proto.set.apply(map, args);
rerender();
if (changed) {
rerender();
}
return map;
};

Expand Down