Hook Master 🚀

useMap

A hook that provides a reactive Map instance with enhanced methods to trigger re-renders on updates

Usage

useMap returns Map. The useMap hook provides a reactive Map instance. It overrides the set, delete, and clear methods to ensure the component re-renders when the map is updated. The hook is initialized with an optional array of key-value pairs.

import { useMap } from 'hook-master-react';
 
function Demo() {
  const map = useMap<string, number>([['a', 1], ['b', 2]]);
 
  return (
    <div>
      <p>Map entries:</p>
      <ul>
        {Array.from(map.entries()).map(([key, value]) => (
          <li key={key}>
            {key}: {value}
          </li>
        ))}
      </ul>
      <button onClick={() => map.set('c', 3)}>Add key 'c'</button>
      <button onClick={() => map.delete('a')}>Remove key 'a'</button>
      <button onClick={() => map.clear()}>Clear map</button>
    </div>
  );
}

Definition

function useMap<T, V>(initialState?: [T, V][]): Map<T, V>;

On this page