StateBeginnerFully SSR-safehooks/state/useMap.ts

useMap

Immutable Map state API.

Import

TypeScript
import { useMap } from '@/hooks';

API

Signature

useMap<K,V>(initial?) → [Map, actions]

When to use

Use useMap instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Fully SSR-safe. Pure React state.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useMap
Editor
function Scores() {
  const [map, actions] = useMap<string, number>([['ada', 10]]);
  return (
    <button onClick={() => actions.set('ada', (map.get('ada') ?? 0) + 1)}>
      ada: {map.get('ada')}
    </button>
  );
}
Preview

Implementation source

Full library source for useMap — copy into your project when you are not installing a package yet.

hooks/state/useMap.ts
import { useCallback, useState } from 'react';

export type MapOrEntries<K, V> = Map<K, V> | readonly (readonly [K, V])[];

export interface UseMapActions<K, V> {
  set: (key: K, value: V) => void;
  setAll: (entries: MapOrEntries<K, V>) => void;
  remove: (key: K) => void;
  reset: () => void;
  clear: () => void;
  get: (key: K) => V | undefined;
  has: (key: K) => boolean;
}

function toMap<K, V>(init?: MapOrEntries<K, V>): Map<K, V> {
  if (!init) return new Map();
  return init instanceof Map ? new Map(init) : new Map(init);
}

/** Map-backed state with immutable updates. */
export function useMap<K, V>(
  initialState?: MapOrEntries<K, V>,
): [Map<K, V>, UseMapActions<K, V>] {
  const [map, setMap] = useState(() => toMap(initialState));

  const actions: UseMapActions<K, V> = {
    set: useCallback((key, value) => {
      setMap((prev) => {
        const next = new Map(prev);
        next.set(key, value);
        return next;
      });
    }, []),
    setAll: useCallback((entries) => {
      setMap(toMap(entries));
    }, []),
    remove: useCallback((key) => {
      setMap((prev) => {
        const next = new Map(prev);
        next.delete(key);
        return next;
      });
    }, []),
    reset: useCallback(() => setMap(toMap(initialState)), [initialState]),
    clear: useCallback(() => setMap(new Map()), []),
    get: useCallback((key) => map.get(key), [map]),
    has: useCallback((key) => map.has(key), [map]),
  };

  return [map, actions];
}

Copy-paste example

useMap.example.tsx
'use client';

import { useMap } from '@/hooks';

export function Scores() {
  const [map, actions] = useMap<string, number>([['ada', 10]]);
  return (
    <button onClick={() => actions.set('ada', (map.get('ada') ?? 0) + 1)}>
      ada: {map.get('ada')}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Keep state setters stable; prefer action helpers over manual setState spreads.
  • Source of truth: open hooks/state/useMap.ts for implementation details