Skip to content
usefy

useMap

State & data

A React hook for managing Map state with immutable updates

Install

$ npm install @usefy/use-map

Quick start

useMap.tsx
import { useMap } from "@usefy/use-map";

function Settings() {
  const [prefs, { set, remove, reset }] = useMap<string, boolean>([
    ["darkMode", false],
    ["beta", true],
  ]);

  return (
    <label>
      <input
        type="checkbox"
        checked={prefs.get("darkMode") ?? false}
        onChange={(e) => set("darkMode", e.target.checked)}
      />
      Dark mode
    </label>
  );
}

API reference

useMap<K, V>(initialState?)

Returns a tuple of the current read-only map and a stable actions object.

Parameters

ParameterTypeDefaultDescription
initialStateMapInitializer<K, V>emptyA Map, an iterable of [key, value] tuples, or a factory returning one (evaluated once)

Returns [map, actions]

ItemTypeDescription
mapReadonlyMap<K, V>Current map. Read via get/has/size/iteration
actionsUseMapActions<K, V>Stable action handlers (see below)

Actions

ActionSignatureDescription
set(key: K, value: V) => voidSet/overwrite a key. Setting a key to its current value is a no-op
setAll(entries: Iterable<[K, V]>) => voidReplace the entire map with the given entries
remove(key: K) => voidRemove a key. Removing an absent key is a no-op
reset() => voidRestore the initial entries (a fresh copy)
clear() => voidRemove all entries. Clearing an empty map is a no-op
get(key: K) => V | undefinedRead a key's value (stable, always reflects latest state)

The returned map is a ReadonlyMap, so calling map.set(...) directly is a TypeScript error. Use the actions — mutating the map in place would bypass React state and break re-renders.


Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in state & data