Open In App

How to Use ES6 Map with React State Hooks?

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, the Map object is a collection of key-value pairs, where keys can be of any data type. In React, managing such key-value pairs with hooks like useState can simplify handling dynamic data structures. React’s state management system allows for smooth and efficient data manipulation, making the ES6 Map a perfect fit when working with key-value relationships in your application.

Prerequisites

Below are the approaches to use ES6 Map with React State Hooks:

Steps to Create and Install Dependencies

Here’s how you can set up a simple React project to use the Map object with state hooks.

Step 1: First, ensure that Node.js is installed on your machine if not installed download from the NodeJs website and verify by running the following command:

node -v
npm -v

Step 2: Once installed, create a new React project using create-react-app

npx create-react-app map-with-react-hooks

Step 3: Navigate to your project directory

cd map-with-react-hooks

Step 4: Install dependencies

npm install

Updated Dependencies:

"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Project Structure:

Map_with_React_folder
Project Structure

Steps to run the project

To run the project use below command

npm start

Managing a Map with useState

You can initialize and update a Map within React's state using the useState hook. This approach involves setting the initial state as a Map and using the state update function to modify it.

Syntax:

const [map, setMap] = useState(new Map());

Example: When you click the Add Item button, the Map updates, and the component renders the new key-value pair.

JavaScript
//src/components/MapComponent
import React, { useState } from 'react';
const MapComponent = () => {
    const [map, setMap] = useState(new Map());
    const addItem = () => {
        const newMap = new Map(map); // Cloning the Map to keep immutability
        newMap.set('key1', 'value1');
        setMap(newMap); // Updating the state
    };
    return (
        <div>
            <button onClick={addItem}>Add Item</button>
            <div>
                {Array.from(map.entries()).map(([key, value]) => (
                    <p key={key}>
                        {key}: {value}
                    </p>
                ))}
            </div>
        </div>
    );
};

export default MapComponent;
JavaScript
// src/App.js
import React from 'react';
import MapComponent from './components/MapComponent';

function App() {
    return (
        <div className="App">
            <MapComponent />
        </div>
    );
}

export default App;

Output:

Updating a Map Immutably

React encourages immutability to ensure components re-render efficiently. To update the Map in state, it’s best to create a copy of the original Map, make updates to the copy, and then update the state with the modified Map.

Syntax:

const [map, setMap] = useState(new Map());

const updateMap = (key, value) => {
const newMap = new Map(map); // Clone existing map
newMap.set(key, value);
setMap(newMap); // Update the state
};

Example: The Update Map button updates the Map with a new key-value pair or modifies an existing one. The component re-renders with the updated values.

JavaScript
//src / components / MapComponent
import React, { useState } from 'react';
const UpdateMapComponent = () => {
    const [map, setMap] = useState(new Map());

    const updateMap = () => {
        const newMap = new Map(map);
        newMap.set('key2', 'new value');
        setMap(newMap);
    };

    return (
        <div>
            <button onClick={updateMap}>Update Map</button>
            <div>
                {Array.from(map.entries()).map(([key, value]) => (
                    <p key={key}>
                        {key}: {value}
                    </p>
                ))}
            </div>
        </div>
    );
};

export default UpdateMapComponent;
JavaScript
// src/App.js
import React from 'react';
import MapComponent from './components/MapComponent';

function App() {
    return (
        <div className="App">
            <MapComponent />
        </div>
    );
}

export default App;

Output:

Using useEffect with Map State

Sometimes, you might want to trigger changes or updates to the Map when specific conditions are met. You can use useEffect to monitor changes and perform side effects based on those changes.

Syntax:

useEffect(() => {
// Perform actions based on `Map` updates
}, [map]);

Example: Each time the Map is updated, the useEffect hook logs the new state of the Map to the console. This can be useful for debugging or for triggering other side effects.

JavaScript
// src/App.js
import React from 'react';
import MapComponent from './components/MapComponent';

function App() {
    return (
        <div className="App">
            <MapComponent />
        </div>
    );
}

export default App;
JavaScript
//src/components/MapComponent
import React, { useState, useEffect } from 'react';
const EffectMapComponent = () => {
    const [map, setMap] = useState(new Map());
    useEffect(() => {
        console.log('Map updated:', map);
    }, [map]);

    const updateMap = () => {
        const newMap = new Map(map);
        newMap.set('key3', 'another value');
        setMap(newMap);
    };
    return (
        <div>
            <button onClick={updateMap}>Update Map with Effect</button>
            <div>
                {Array.from(map.entries()).map(([key, value]) => (
                    <p key={key}>
                        {key}: {value}
                    </p>
                ))}
            </div>
        </div>
    );
};

export default EffectMapComponent;

Output:

Iterating Over Map Data in a Component

To render the contents of a Map in your component, you can iterate over it using Array.from(map.entries()) or directly using map.forEach.

Array.from(map.entries()).map(([key, value]) => {
// Render logic
});

Example: This approach renders all the key-value pairs inside the Map and displays them as a list.

JavaScript
//src/components/MapComponent
import React, { useState } from 'react';
const RenderMapComponent = () => {
    const [map, setMap] = useState(new Map([['key1', 'value1'], ['key2', 'value2']]));

    return (
        <div>
            <div>
                {Array.from(map.entries()).map(([key, value]) => (
                    <p key={key}>
                        {key}: {value}
                    </p>
                ))}
            </div>
        </div>
    );
};

export default RenderMapComponent;
JavaScript
// src/App.js
import React from 'react';
import MapComponent from './components/MapComponent';

function App() {
    return (
        <div className="App">
            <MapComponent />
        </div>
    );
}

export default App;

Output:

JavaScript_Map_project_output_4
Ouput

Conclusion

Using the ES6 Map with React state hooks allows developers to manage key-value pairs in a clean, efficient manner. By using useState to manage Map objects, ensuring immutability during updates, and taking advantage of hooks like useEffect, you can create flexible and dynamic components.


Next Article
Article Tags :

Similar Reads