One potential advantage of a Map is that its keys can be of any type - unlike plain objects, in which a key may only be a string or a symbol. Something else to consider is that plain objects with dynamic keys can rarely be problematic due to property name collisions (__proto__
, valueOf
, etc).
That said, in React, a Map probably isn't that great of an idea:
In React, state should never be mutated, but if you use a Map, you'll probably be very tempted to use methods like Map.set
- which mutates it. You'll have to remember to clone the map first every time.
You won't be able to do
setState({ ...stateObj, [prop]: newVal })
but instead
setState(new Map(stateMap).set(prop, newVal))
Iterating through Maps is somewhat cumbersome because the only way to do so is through their iterators (.entries
, .keys
, .values
) - but iterators aren't arrays and can't be .map
ped to JSX immediately. Every time you want to do something with the Map, you'd have to turn it into an array instead: [...myMap.entries()].map((key, value) =>
which is a bit ugly.
If dynamic keys are something to worry about, you can use an array instead: const mapper = [{ key: 'foo', value: 'bar' } ...
without having to use a Map.
It's not that a Map can't be implemented properly, or that a plain object can't either - you just have to be careful.