日本語

How to Use a Map in React State and Update It with a New Map

​​React​JavaScript,Playwright,TypeScript,useState

When you keep per-id values in React state, such as the quantity of each product in a shopping cart, you can use a Map<id, value>. To update it, create a new Map that copies the contents with new Map(prev), call set() or delete() on that new Map, and pass it to the setter. If you modify the same Map and pass it back, React considers the value unchanged and the screen does not update.

I built a cart that increases and decreases the quantity of each product, put the correct way and the mutating way side by side, and checked the behavior in Chromium.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and ran the development build under StrictMode. I also tried the update-style comparison with the production build. I did not test Firefox, Safari, mobile browsers, or combinations with useReducer or state management libraries.

The cart screen. Notebook 2, ballpoint pen 2, eraser 1, each with − and + buttons. Below is the Japanese label meaning "3 kinds / total 690 yen" and the Map contents [[1,2],[2,2],[3,1]]
A cart whose number of kinds and total are computed from the quantities held in a Map

Holding quantities per product id in a Map

I moved the logic for changing a quantity out of React into a function. It leaves the original Map unchanged and returns a new Map.

ts
// quantities.ts
// Returns a new Map of quantities per product id (does not change the original Map)
export function setQuantity(
  prev: ReadonlyMap<number, number>,
  id: number,
  quantity: number,
): Map<number, number> {
  const next = new Map(prev); // A separate Map with the same contents
  if (quantity <= 0) {
    next.delete(id); // When it reaches 0, remove the key itself
  } else {
    next.set(id, quantity);
  }
  return next;
}

As described in MDN's explanation of cloning Maps, passing a Map to new Map() creates a different Map with the same keys and values. In Node.js, I created m from new Map([[1, 2]]) and called set(2, 5), then copied it. Calling set() on the copy did not change the original, and Object.is reported them as different objects.

txt
コピー c = [[1,99],[2,5]]  元の m = [[1,2],[2,5]]
Object.is(m, c) = false

In the component, this function is called inside the updater function passed to setQuantities. Products with a quantity of 0 have no key, so quantities.size is directly the number of kinds in the cart.

tsx
// Cart.tsx
import { useState } from 'react';
import { setQuantity } from './quantities';

type Product = { id: number; name: string; price: number };

export function Cart({ products }: { products: readonly Product[] }) {
  // Product id → quantity. Products not in the cart have no key
  const [quantities, setQuantities] = useState<ReadonlyMap<number, number>>(() => new Map());

  const change = (id: number, quantity: number) => {
    setQuantities((prev) => setQuantity(prev, id, quantity));
  };

  const total = products.reduce((sum, p) => sum + p.price * (quantities.get(p.id) ?? 0), 0);

  return (
    <div className="cart">
      <ul>
        {products.map((p) => {
          const quantity = quantities.get(p.id) ?? 0;
          return (
            <li key={p.id}>
              <span className="name">{p.name}</span>
              <button type="button" aria-label={`${p.name}を減らす`} onClick={() => change(p.id, quantity - 1)}>
                −
              </button>
              <output>{quantity}</output>
              <button type="button" aria-label={`${p.name}を増やす`} onClick={() => change(p.id, quantity + 1)}>
                +
              </button>
            </li>
          );
        })}
      </ul>
      <p className="summary">
        {quantities.size}種類 / 合計 {total.toLocaleString('ja-JP')}円
      </p>
      <p className="entries">中身: {JSON.stringify([...quantities])}</p>
    </div>
  );
}

These are the results of passing three products, notebook (id 1, 180 yen), ballpoint pen (id 2, 120 yen), and eraser (id 3, 90 yen), and pressing the buttons with Playwright. The Display column shows the English meaning of the Japanese text on screen (kinds / total in yen).

Operation Display (translated) Map contents
Initial 0 kinds / total 0 yen []
Notebook + twice 1 kind / total 360 yen [[1,2]]
Eraser + 2 kinds / total 450 yen [[1,2],[3,1]]
Ballpoint pen + 3 kinds / total 570 yen [[1,2],[3,1],[2,1]]
Eraser − 2 kinds / total 480 yen [[1,2],[2,1]]
Eraser + 3 kinds / total 570 yen [[1,2],[2,1],[3,1]]
Ballpoint pen + 3 kinds / total 690 yen [[1,2],[2,2],[3,1]]

When the eraser went to 0, its key was removed, and the number of kinds dropped to 2. The console had no errors or warnings.

The order of entries in the Map is not id order but insertion order. As described in MDN's explanation of Map, a Map keeps keys in the order they were first set(). I removed the eraser and added it back, so it moved after the ballpoint pen. Calling set() on the ballpoint pen's existing key did not change its position. The rows on screen are rendered in the order of products, so this order does not affect the display. You can also use the Map order as "the order items were added to the cart."

If you mutate the same Map, the screen does not change

The set function reference for useState says that if the new value is the same as the current one by Object.is, React skips the re-render. Map's set() only changes the contents of the same Map, and its return value is that Map itself (in Node.js, m.set(2, 5) === m was also true). Passing it back makes React see the "same value."

To confirm this, I wrote three updater functions that each increment the count for id 1, and tested each with its own state.

tsx
// Mutate.tsx (to check how the screen changes depending on how the Map is updated)
import { useState } from 'react';

type Updater = (prev: Map<number, number>) => Map<number, number>;

// 1. Mutate the same Map and return it as is
const sameMap: Updater = (prev) => {
  prev.set(1, (prev.get(1) ?? 0) + 1);
  return prev;
};

// 2. Mutate the same Map, then return a copy
const mutateThenCopy: Updater = (prev) => {
  prev.set(1, (prev.get(1) ?? 0) + 1);
  return new Map(prev);
};

// 3. Create a copy, then set on the copy
const copyThenSet: Updater = (prev) => new Map(prev).set(1, (prev.get(1) ?? 0) + 1);

function Counter({ label, update }: { label: string; update: Updater }) {
  const [counts, setCounts] = useState<Map<number, number>>(() => new Map());
  return (
    <div className="counter" data-label={label}>
      <button type="button" onClick={() => setCounts(update)}>
        {label}
      </button>
      <output>{counts.get(1) ?? 0}</output>
    </div>
  );
}

These are the displayed values after pressing each button three times.

Updater function Development build (StrictMode) Production build
1. Return the same Map 0 → 0 → 0 0 → 0 → 0
2. Mutate, then return a copy 1 → 3 → 5 1 → 2 → 3
3. Copy, then set 1 → 2 → 3 1 → 2 → 3

With the first one, the display stayed at 0 in both builds.

The second one returns a new Map, so the screen does change. But in the development build, the first press showed 1, and from the second press on, it went up by 2 each time. The useState reference says that under StrictMode, the updater function is called twice to check that it is pure, and one of the results is discarded. The second updater function mutates the prev it receives. So the mutation from the call whose result is discarded also stays in prev, and the count goes up extra. In the production build, it went up by 1 each time, so this pattern is easy to miss if you only run the production build.

The third one increased by 1 in both builds. Since set() returns the Map, you can also write it on one line as new Map(prev).set(...).

Point

Do not call set() or delete() on the Map in prev. Change only a copy made with new Map(prev).

The official React documentation on updating objects in state also says to treat objects in state as read-only, and to create a new object and replace it rather than mutate it. A Map should be handled the same way.

Using ReadonlyMap turns mutation into a type error

In Cart.tsx, I typed the state as ReadonlyMap<number, number>. ReadonlyMap has no set() or delete(), so code that mutates it by mistake is stopped by tsc. I wrote the following code in check/readonly.ts and type-checked it with tsc.

ts
// Check whether calling set() on a ReadonlyMap state is a type error
const quantities: ReadonlyMap<number, number> = new Map([[1, 2]]);
quantities.set(1, 3);
quantities.delete(1);
const copy = new Map(quantities); // The copy is a Map, so set() is allowed
copy.set(1, 3);
quantities.get('1'); // Calling get() with a string id
txt
check/readonly.ts(3,12): error TS2339: Property 'set' does not exist on type 'ReadonlyMap<number, number>'.
check/readonly.ts(4,12): error TS2339: Property 'delete' does not exist on type 'ReadonlyMap<number, number>'.
check/readonly.ts(7,16): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
exit: 1

The set() and delete() lines were errors, and set() on the copy passed. This is also why setQuantity takes a ReadonlyMap as its argument and returns a new Map. The TS2345 on the last line is an error from passing a string as the key (covered in the next section).

Pitfalls when using a Map as state

Numeric and string keys are different

As described in MDN, Map keys are compared almost the same way as ===. The number 1 and the string "1" are different keys.

txt
m.get(1) = 2  m.get("1") = undefined
m.get(Number("2")) = 5

The data-id value read through dataset, and URL parameters obtained with URLSearchParams.get(), are strings. If your keys are numbers, convert with Number() before calling get(). Passing a string to a Map whose keys are typed as number produces the TS2345 error shown in the tsc result in the previous section.

Unlike objects, numeric keys are also kept in insertion order

I put the same keys into a Map and into an object, and compared the key order.

txt
Map のキー = [30,2,10]
オブジェクトのキー = ["2","10","30"]

With the object, the keys became strings, and integer keys were reordered from smallest to largest. A Map keeps both the key types and the insertion order.

JSON.stringify drops the contents

Passing a Map directly to JSON.stringify() gave {}. If you serialize it to a string and save it to localStorage or similar, the contents are lost.

txt
JSON.stringify(map) = {}
JSON.stringify([...map]) = [[30,"c"],[2,"a"],[10,"b"]]
戻した Map の get(2) = a
Object.fromEntries(map) = {"2":"a","10":"b","30":"c"}

If you save [...map], which is an array of [key, value] pairs, and pass the parsed result to new Map(JSON.parse(...)) when loading, the numeric keys are restored as numbers. Converting to an object with Object.fromEntries() turns the keys into strings and changes their order. The entries line in the cart (labeled 中身:, meaning "contents") is also JSON.stringify() applied to [...quantities].

The copy made by new Map(prev) is shallow

As also noted in MDN, new Map(prev) copies only the key-value pairs (a shallow copy). When the values are objects, the copied Map still points to the same objects.

txt
浅いコピー:rows.get(1) === rowsCopy.get(1) = true

If the values are objects, you need to do more than copy the Map: create a new object for the value you change, such as { ...old, note: '新しいメモ' }, and then call set(). Applying the same idea inside objects is the same as updating items in an array state.

​Posted by 86