useMap

Manage a Map state.

https://www.shaktools.com/shak-hooks
State

API Reference

Installation

terminal
pnpm add @shak-hooks/usehooks
import.ts
import { useMap } from "@shak-hooks/usehooks";
Source: packages/react/src/useMap.ts

Signature

signature.ts
export function useMap<K, V>(initialValue?: Iterable<readonly [
K,
V
]>)

Parameters

NameTypeOptionalDefault
initialValueIterable<readonly [ K, V ]>Yes-

Returns

unknown

Implementation

use-map.ts
1import { useState, useCallback } from "react";
2
3export function useMap<K, V>(initialValue: Map<K, V> = new Map()) {
4 const [map, setMap] = useState(initialValue);
5
6 const set = useCallback((key: K, value: V) => {
7 setMap((prev) => {
8 const copy = new Map(prev);
9 copy.set(key, value);
10 return copy;
11 });
12 }, []);
13
14 const setAll = useCallback((newMap: Map<K, V>) => {
15 setMap(new Map(newMap));
16 }, []);
17
18 const remove = useCallback((key: K) => {
19 setMap((prev) => {
20 const copy = new Map(prev);
21 copy.delete(key);
22 return copy;
23 });
24 }, []);
25
26 const reset = useCallback(() => {
27 setMap(initialValue);
28 }, [initialValue]);
29
30 return [map, { set, setAll, remove, reset }] as const;
31}

Advertisement

Google Ads

Usage

example.tsx
1import { useMap } from "@shak-hooks/usehooks";
2
3const result = useMap(undefined);
4// result: unknown
5// Use values directly (React state).

Let‘s do great work together

Empowering creators with free, high-performance AI, SEO, and developer tools. Join thousands of users optimizing their workflow with Shak-Tools.

Tools10+ Free
UsersGlobal

Stay in the loop

Join our newsletter for the latest AI tools and updates.

ShakTools
© 2025 Shaktools. All Rights Reserved.Privacy Policy