It takes as initial entries a Map or an array like [["key": "value"], [..]] or nothing and returns:
- An array with an instance of
Map(including:foreach, get, has, entries, keys, values, size) - And an object of methods (
set, setAll, remove, reset)
Make sure to use these methods to update the map, a map.set(..) would not re-render the component.
Why use Map instead of an object ?
Map is an iterable, a simple hash and it performs better in storing large data (Read more).
Usage
import { Fragment } from 'react'
import { useMap } from './useMap'
export default function Component() {
const [map, actions] = useMap<string, string>([['key', '🆕']])
const set = () => {
actions.set(String(Date.now()), '📦')
}
const setAll = () => {
actions.setAll([
['hello', '👋'],
['data', '📦'],
])
}
const reset = () => {
actions.reset()
}
const remove = () => {
actions.remove('hello')
}
return (
<div>
<button onClick={set}>Add</button>
<button onClick={reset}>Reset</button>
<button onClick={setAll}>Set new data</button>
<button onClick={remove} disabled={!map.get('hello')}>
{'Remove "hello"'}
</button>
<pre>
Map (
{Array.from(map.entries()).map(([key, value]) => (
<Fragment key={key}>{`\n ${key}: ${value}`}</Fragment>
))}
<br />)
</pre>
</div>
)
}
API
function useMap(initialState?: MapOrEntries<K, V>): UseMapReturn<K, V>
Custom hook that manages a key-value Map state with setter actions.
Parameters
| Name | Type | Default value | Description |
|---|---|---|---|
initialState? | MapOrEntries<K, V> | ... | The initial state of the map as a Map or an array of key-value pairs (optional). |
Returns
A tuple containing the map state and actions to interact with the map.
Type declaration
MapOrEntries
Represents the type for either a Map or an array of key-value pairs.
UseMapActions
Represents the actions available to interact with the map state.
| Name | Type | Description |
|---|---|---|
remove | (key: K) => void | Remove a key-value pair from the map. |
reset | unknown | Reset the map to an empty state. |
set | (key: K, value: V) => void | Set a key-value pair in the map. |
setAll | (entries: MapOrEntries<K, V>) => void | Set all key-value pairs in the map. |
UseMapReturn
Represents the return type of the useMap hook. We hide some setters from the returned map to disable autocompletion.
Hook
import { useCallback, useState } from 'react'
/**
* Represents the type for either a Map or an array of key-value pairs.
* @template K - The type of keys in the map.
* @template V - The type of values in the map.
*/
export type MapOrEntries<K, V> = Map<K, V> | [K, V][]
/**
* Represents the actions available to interact with the map state.
* @template K - The type of keys in the map.
* @template V - The type of values in the map.
*/
export type UseMapActions<K, V> = {
/** Set a key-value pair in the map. */
set: (key: K, value: V) => void
/** Set all key-value pairs in the map. */
setAll: (entries: MapOrEntries<K, V>) => void
/** Remove a key-value pair from the map. */
remove: (key: K) => void
/** Reset the map to an empty state. */
reset: Map<K, V>['clear']
}
/**
* Represents the return type of the `useMap` hook.
* We hide some setters from the returned map to disable autocompletion.
* @template K - The type of keys in the map.
* @template V - The type of values in the map.
*/
export type UseMapReturn<K, V> = [
Omit<Map<K, V>, 'set' | 'clear' | 'delete'>,
UseMapActions<K, V>,
]
/**
* Custom hook that manages a key-value [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) state with setter actions.
* @template K - The type of keys in the map.
* @template V - The type of values in the map.
* @param {MapOrEntries<K, V>} [initialState] - The initial state of the map as a Map or an array of key-value pairs (optional).
* @returns {UseMapReturn<K, V>} A tuple containing the map state and actions to interact with the map.
* @public
* @see [Documentation](https://usehooks-ts.com/react-hook/use-map)
* @example
* ```tsx
* const [map, mapActions] = useMap();
* // Access the `map` state and use `mapActions` to set, remove, or reset entries.
* ```
*/
export function useMap<K, V>(
initialState: MapOrEntries<K, V> = new Map(),
): UseMapReturn<K, V> {
const [map, setMap] = useState(new Map(initialState))
const actions: UseMapActions<K, V> = {
set: useCallback((key, value) => {
setMap(prev => {
const copy = new Map(prev)
copy.set(key, value)
return copy
})
}, []),
setAll: useCallback(entries => {
setMap(() => new Map(entries))
}, []),
remove: useCallback(key => {
setMap(prev => {
const copy = new Map(prev)
copy.delete(key)
return copy
})
}, []),
reset: useCallback(() => {
setMap(() => new Map())
}, []),
}
return [map, actions]
}