'Is there any benefit in using Map (Object) over objects in React functional components? [duplicate]
I couldn't find anything about this online but I recently saw some React examples using the Map object to make a simple mapper. This had me wondering if there is some kind of benefit to using the Map object rather than a plain javascript object {} in React functional components.
Are there any noteworthy difference between these two examples?
function myFunctionalComponent() {
const mapper = {
foo: 'bar',
fizz: 'buzz'
};
}
function myFunctionalComponent() {
const mapper = new Map([
['foo', 'bar',],
['fizz', 'buzz']
]);
}
Solution 1:[1]
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.mapped 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
