0

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']
    ]);
}
0

1 Answer 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.

Sign up to request clarification or add additional context in comments.

2 Comments

I appreciate the quick response! I figured there wouldn't be much noticeable difference in terms of React. These are all very insightful points, thank you.
DV because this response fails to make a meaningful comparison to plain objects. Both are mutable. Neither has an array-like map function. If anything, for (const [k, v] of myMap) and [...myMap].map(...) are less "ugly" and "cumbersome" than for (const [k,v] of Object.entries(myMap)) and Object.entries(myMap).map(...).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.