Skip to main content

useMap

React state hook that manages a Map

Usage

Live Editor
function Demo() {
  const { map, set, get, remove, has, clear, reset, size } = useMap([
    ['react', '18.0.0'],
    ['vue', '3.0.0'],
  ]);

  return (
    <div>
      <p>Map size: {size}</p>
      <div style={{ marginBottom: 16 }}>
        <button
          type="button"
          onClick={() => set('angular', '16.0.0')}
          style={{ marginRight: 8 }}
        >
          Add Angular
        </button>
        <button
          type="button"
          onClick={() => set('react', '18.2.0')}
          style={{ marginRight: 8 }}
        >
          Update React
        </button>
        <button
          type="button"
          onClick={() => remove('vue')}
          style={{ marginRight: 8 }}
        >
          Remove Vue
        </button>
        <button
          type="button"
          onClick={clear}
          style={{ marginRight: 8 }}
        >
          Clear All
        </button>
        <button
          type="button"
          onClick={reset}
          style={{ marginRight: 8 }}
        >
          Reset
        </button>
      </div>
      <div>
        <p>Current entries:</p>
        <ul>
          {Array.from(map.entries()).map(([key, value]) => (
            <li key={key}>
              {key}: {value} 
              {has(key) && ' ✓'}
            </li>
          ))}
        </ul>
      </div>
      <div>
        <p>Get React version: {get('react') || 'Not found'}</p>
      </div>
    </div>
  );
};
Result

Map size: 2

Current entries:

  • react: 18.0.0 ✓
  • vue: 3.0.0 ✓

Get React version: 18.0.0

API

useMap

Returns

{ readonly map: Map<K, V>; readonly set: (key: K, value: V) => void; readonly get: (key: K) => V | undefined; readonly remove: (key: K) => boolean; readonly has: (key: K) => boolean; readonly clear: () => void; readonly reset: () => void; readonly size: number; }: An object with the following properties:

  • map: The current Map instance.
  • set: A function to set a key-value pair in the map.
  • get: A function to get a value by key from the map.
  • remove: A function to remove a key from the map and return whether it existed.
  • has: A function to check if a key exists in the map.
  • clear: A function to clear all entries from the map.
  • reset: A function to reset the map to its initial state.
  • size: The current size of the map.

Arguments

ArgumentDescriptionTypeDefaultValue
initialValueThe initial value of the map. It can be a Map instance, an array of key-value pairs, or a function that returns initial entries.Map<K, V> | readonly (readonly [K, V])[] | (() => Map<K, V> | readonly (readonly [K, V])[]) | undefined-
Auth0
Your time is valuable. Use it to focus on your app, and let us handle login (and much more).
Try for Free Now