Rooks
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

ParameterTypeDefaultDescription
initialValueT extends Record<string, unknown>RequiredObject 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.

MethodTypeBehavior
set(key: K, value: T[K]) => voidReplaces one property.
has(key: K) => booleanReports whether the current property value is not undefined.
setMultiple(next: Partial<T>) => voidShallow-merges several properties in one state update.
remove(key: K) => voidDeletes one property.
removeMultiple(...keys: K[]) => voidDeletes each supplied property in one state update.
removeAll() => voidDeletes 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 has are stable. has is recreated when the object changes because it reads the latest value.
  • has is value-based: a property whose value is undefined is reported as absent. Removal works even when the object contains a key named hasOwnProperty.

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.

useObjectState is a supported alias of this hook.

On this page