HooksState Management
useMapState
Manages a record-like object as React state with keyed update and removal helpers.
About
useMapState manages a string-keyed object with stable helpers for reading, merging, and removing properties. Despite the historical name, it does not store or return a JavaScript Map; use useNativeMapState when you need that data structure.
Examples
import { useMapState } from "rooks";
const initialLabels: Record<string, string> = { primary: "blue" };
export default function Labels() {
const [labels, { remove, set }] = useMapState(initialLabels);
return (
<section>
<p>{JSON.stringify(labels)}</p>
<button type="button" onClick={() => set("accent", "violet")}>
Set accent
</button>
<button type="button" onClick={() => remove("accent")}>
Remove accent
</button>
</section>
);
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | T extends Record<string, unknown> | Required | Object used for the initial state. The hook keeps the same property types. |
Return value
Returns [value, methods]. value has the same object type as initialValue.
| Method | Type | Behavior |
|---|---|---|
set | (key: K, value: T[K]) => void | Replaces one property. |
has | (key: K) => boolean | Reports whether the current property value is not undefined. |
setMultiple | (next: Partial<T>) => void | Shallow-merges several properties in one state update. |
remove | (key: K) => void | Deletes one property. |
removeMultiple | (...keys: K[]) => void | Deletes each supplied property in one state update. |
removeAll | () => void | Deletes every own enumerable property and leaves an empty object. |
Behavior and lifecycle
- Updates use React functional state setters, so consecutive helper calls merge against the latest committed state.
- Every update creates a new object with a shallow spread; nested values are not cloned.
- Helper functions other than
hasare stable.hasis recreated when the object changes because it reads the latest value. hasis value-based: a property whose value isundefinedis reported as absent. Removal works even when the object contains a key namedhasOwnProperty.
Compatibility and accessibility
The hook uses only React state and is safe to render on the server. It has no browser API or permission requirement. Accessibility depends on the controls that consume the state; label those controls and announce state changes when users need immediate feedback.
Related
useObjectState is a supported alias of this hook.