Docs
useMap
Synchronize and update state based on the Map data structure with useMap.
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-map
Usage
"use client"
import { useMap } from "@/hooks/use-map"
type TeamName = "Jazz" | "Suns"
export function Component() {
const map = useMap<TeamName, number>([
["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 onClick={() => map.set(team, score + 2)}>+ 2</button>
</td>
<td style={{ width: "12.5%" }}>
<button onClick={() => map.set(team, score + 3)}>+ 3</button>
</td>
</tr>
)
})}
</tbody>
</table>
</section>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
initialState | Iterable<[K, V]> | The initial value for the map. Defaults to an empty map ([] ). | [] | Yes |
Return Values
Name | Type | Description |
---|---|---|
set | (key: K, value: V) => this | Adds or updates a key-value pair in the map. Triggers a re-render. |
delete | (key: K) => boolean | Removes a key-value pair from the map. Triggers a re-render. Returns true if the key existed, otherwise false . |
clear | () => void | Clears the map, removing all key-value pairs. Triggers a re-render. |