useMap
Synchonize and update state based on the Map data structure with useMap.
Install:
npm i @uidotdev/usehooks
Description:
The useMap hook provides a wrapper around the JavaScript Map object and allows you to easily update and synchronize the map state with the component’s rendering. By using this hook, you can add, delete, or clear entries in the map while ensuring that the component re-renders whenever these operations are performed.
Return Value
Name | Type | Description |
---|---|---|
map | map object | An instance of the Map object with enhanced methods. |
Demo:
Example:
import * as React from "react";
import { useMap } from "@uidotdev/usehooks";
export default function App() {
const map = useMap([
["Jazz", 32],
["Suns", 50],
]);
return (
<section>
<h1>useMap</h1>
<table>
<thead>
<tr>
<th colSpan={4}>Jazz vs Suns</th>
</tr>
</thead>
<tbody>
{Array.from(map.keys()).map((team) => {
const score = map.get(team);
return (
<tr key={team}>
<th style={{ width: "25%" }}>{team}</th>
<td style={{ width: "50%" }}>{score}</td>
<td style={{ width: "12.5%" }}>
<button
className="link"
onClick={() => {
map.set(team, score + 2);
}}
>
+ 2
</button>
</td>
<td style={{ width: "12.5%" }}>
<button
className="link"
onClick={() => {
map.set(team, score + 3);
}}
>
+ 3
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</section>
);
}