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

NameTypeDescriptionDefault ValueOptional
initialStateIterable<[K, V]>The initial value for the map. Defaults to an empty map ([]).[]Yes

Return Values

NameTypeDescription
set(key: K, value: V) => thisAdds or updates a key-value pair in the map. Triggers a re-render.
delete(key: K) => booleanRemoves a key-value pair from the map. Triggers a re-render. Returns true if the key existed, otherwise false.
clear() => voidClears the map, removing all key-value pairs. Triggers a re-render.