Hook that stores a Map in state and updates it immutably
A file uploader tracks the progress of every file by its id: Map { 'f1' => 40, 'f2' => 100 }. A Map is a good fit (any key type, insertion order, fast lookups), but React only re-renders when state changes identity, so calling map.set(...) on the stored map does nothing on screen. Copying the map on every update fixes that, but copying when nothing changed makes memoized rows re-render for no reason. Implement a React hook, useMapState, that keeps a Map in state and updates it immutably.
function useMapState<K, V>(
initial?: Iterable<[K, V]> | (() => Iterable<[K, V]>),
): [
map: ReadonlyMap<K, V>,
actions: {
set: (key: K, value: V) => void;
update: (key: K, updater: (current: V | undefined) => V) => void;
remove: (...keys: K[]) => void;
clear: () => void;
reset: () => void;
},
]
initial: the starting entries: an array of [key, value] pairs, a Map, any iterable of pairs, or a function that returns one. Defaults to no entries.Map the caller passed in. If initial is a function, call it only once, on the first render.set(key, value) adds the key or replaces its value. update(key, updater) sets the key to updater(currentValue), where currentValue is undefined if the key is missing.remove(...keys) deletes every given key. Missing keys are ignored.clear() removes every entry. reset() goes back to the initial entries.Map. A map you have already returned must never change.set/update with a value that is Object.is-equal to the existing value of an existing key, remove where none of the keys exist, and clear on an empty map.Map behaviour).actions object (and each function in it) keeps the same identity on every render.const [progress, { set, update, remove, clear, reset }] = useMapState([['f1', 0], ['f2', 0]]);
set('f1', 40); // Map { f1 => 40, f2 => 0 }
update('f2', (p) => (p ?? 0) + 25); // Map { f1 => 40, f2 => 25 }
update('f3', (p) => (p ?? 0) + 10); // Map { f1 => 40, f2 => 25, f3 => 10 }
set('f1', 40); // no change: the same Map instance is kept
remove('f2', 'f9'); // Map { f1 => 40, f3 => 10 }
clear(); // Map {}
clear(); // no change: the same (empty) Map instance is kept
reset(); // Map { f1 => 0, f2 => 0 }
ReactDOM.flushSync. The tests compare map contents with [...map] and map identity with ===.Object.assign(window, { useMapState }); below “Do not edit below this line”. The tests use it to call your hook.