How to Use a Map With React useState() Hook?

In React, managing state is crucial for building dynamic and interactive user interfaces. The useState() hook offers a convenient way to handle state within functional components. While often used with primitive values or objects, you can also employ more intricate data structures like maps.

To learn more about using Map with useState(), you can go through the following topics:

  1. Initializing useState() With Map;
  2. Adding and Removing Items;
  3. Rendering Map Contents;
  4. Example.

Maps are versatile data structures in JavaScript that store key-value pairs, providing efficient data retrieval. Integrating maps with the React useState() hook enables the management of such key-value collections within components.

Initializing useState() With Map

To use a Map with useState(), you can initialize the state with a new instance of a Map, like so:

// initialize state with a new `Map` instance
const [myMap, setMyMap] = useState(new Map());

This sets up the initial state as an empty Map, ready to store key-value pairs.

Adding and Removing Items

To add or remove items within a Map, you can use the setter function provided by useState() in the updater function form to ensure proper state management.

For example, to add a new key-value pair to the Map you can do the following:

const addItemToMap = (key, value) => {
  setMyMap((prevMap) => new Map(prevMap.set(key, value)));
};

Similarly, to remove an item from the Map you can do the following:

const removeItemFromMap = (key) => {
  setMyMap((prevMap) => {
    // 1: create a new `Map` based on the previous `Map`
    const newMap = new Map(prevMap);
    // 2: remove the item from the new `Map`
    newMap.delete(key);
    // 3: return the new `Map`
    return newMap;
  });
};

Rendering Map Contents

To display the contents of the Map within your component, you can convert the Map to an array of entries and then iterate over them:

<div>
  {Array.from(myMap.entries()).map(([key, value]) => (
    <div key={key}>
      {`${key}: ${value}`}
    </div>
  ))}
</div>

Example

Below is a complete example, demonstrating the use of a Map with the useState() hook:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [myMap, setMyMap] = useState(new Map());

  useEffect(() => {
    console.log('Map was updated', myMap);
  }, [myMap]);

  const addItemToMap = (key, value) => {
    setMyMap((prevMap) => new Map(prevMap.set(key, value)));
  };

  const removeItemFromMap = (key) => {
    setMyMap((prevMap) => {
      const newMap = new Map(prevMap);
      newMap.delete(key);
      return newMap;
    });
  };

  return (
    <div>
      <button onClick={() => addItemToMap('foo', 'bar')}>Add Item#1</button>
      <button onClick={() => addItemToMap('baz', 'qux')}>Add Item#2</button>
      <button onClick={() => removeItemFromMap('foo')}>Remove Item#1</button>
      <button onClick={() => removeItemFromMap('baz')}>Remove Item#2</button>
      <div>
        {Array.from(myMap.entries()).map(([key, value]) => (
          <div key={key}>{`${key}: ${value}`}</div>
        ))}
      </div>
    </div>
  );
}

export default MyComponent;

In this example:

  1. The state "myMap" is initialized to an empty Map using useState();
  2. The "addItemToMap()" and "removeItemFromMap()" add and remove key-value pairs from the Map respectively;
  3. These functions create a copy of the current Map, perform the necessary operation, and then update the state with the new Map;
  4. The JSX renders buttons to demonstrate adding and removing key-value pairs, along with displaying the contents of the Map;
  5. Lastly, Array.from() is used to convert Map to array to iterate over it and render all its key-value pairs.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.