Skip to content

useMap

Hook to use Map data structure to handle component state with all Map methods.

Demo

INFO

The component has:

  • A useMap internal state.
  • An uncontrolled input with inputRef ref used to execute buttons actions.
  • A button Set that set the input value (format like id - value) into state by set method of Map interface.
  • A button Delete that remove item into state by key, written in input by delete method of Map interface.
  • A button Clear that clear state by clear method of Map interface.
  • A button IncrementAll that adds 1 to every value into map by forEach method of Map interface.
  • A variable parsed create with useMemo that memoized a concatenated string of state key-value pairs, separated by comma.
Loading demo…
Show source code
tsx
import { useCallback, useMemo, useRef } from "react";
import { useMap } from "../../../..";

const UseMap = () => {
	const map = useMap<string, number>();

	const inputRef = useRef<HTMLInputElement>(null);

	const del = useCallback(() => {
		map.delete(inputRef.current!.value);
	}, [map]);

	const set = useCallback(() => {
		const [key, value] = inputRef.current!.value.split("-");
		map.set(key, Number(value));
	}, [map]);

	const clear = useCallback(() => {
		map.clear();
	}, [map]);

	const incrementAll = useCallback(() => {
		map.forEach((value, key, map) => { map.set(key, value + 1) });
	}, [map]);

	const parsed = useMemo(() => {
		const temp: string[] = [];
		temp.map
		map.forEach((value, key) => temp.push(key + " - " + value));
		return temp.join(", ");
	}, [map]);

	return (<>
		{parsed}
		<br/>
		<input ref={inputRef} type="text" />
		<br />
		<div style={{ marginTop: 15, gridTemplateColumns: 'auto auto', justifyContent: 'center', display: 'grid', gap: '5px' }}>
			<button onClick={set}>Set</button>
			<button onClick={del}>Delete</button>
			<button onClick={clear}>Clear</button>
			<button onClick={incrementAll}>Increment all</button>
		</div>
	</>);
}

UseMap.displayName = "UseMap";

export {UseMap}

Types

UseMapProps

  • @template K - The type of the map keys.
  • @template V - The type of the map values.

Parameters accepted by useMap.

PropertyTypeRequiredDescription
initialStateIterable<readonly [K, V]> \| (() => Iterable<readonly [K, V]>)The initial entries of the map. Accepts any Iterable of [key, value] pairs (e.g. an array of tuples, another Map, or a generator) or a lazy initializer function returning such an iterable, invoked only on the first render. When omitted, the map is initialised as empty.

UseMapResult

  • @template K - The type of the map keys.
  • @template V - The type of the map values.

Return value of useMap. A reactive Map<K, V> whose mutating methods automatically synchronise the underlying React state. All standard read-only methods (get, has, keys, values, entries, forEach, etc.) are inherited unchanged from Map<K, V>. The following mutating methods are overridden to trigger a re-render:

MethodBehaviour
setAdds or updates the entry for key, triggers a re-render, returns the map.
clearRemoves all entries and triggers a re-render.
deleteRemoves the entry for key and triggers a re-render. Returns true if the key existed, false otherwise.
ts
export type UseMapResult<K, V> = Map<K, V> & {
	/**
	 * Adds or updates the entry for `key` with `value`, triggers a re-render,
	 * and returns the updated map.
	 */
	set(key: K, value: V): Map<K, V>;

	/** Removes all entries from the map and triggers a re-render. */
	clear(): void;

	/**
	 * Removes the entry for `key` and triggers a re-render. Returns `true` if
	 * the key existed in the map before deletion, `false` otherwise.
	 */
	delete(key: K): boolean;
};

Released under the MIT License.