Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Last active April 18, 2024 03:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophemarois/3f13453491605d91d062721d9822d49c to your computer and use it in GitHub Desktop.
Save christophemarois/3f13453491605d91d062721d9822d49c to your computer and use it in GitHub Desktop.
React hook for state using ES6 Map
import { useState } from 'react'
export default function useMap<K, V>(): [
Map<K, V>,
{
set: (key: K, value: V) => void
unset: (key: K) => void
clear: () => void
}
] {
const [state, setState] = useState<Map<K, V>>(new Map())
const set = (key: K, value: V) => {
setState((prev) => {
const clone = new Map(prev)
clone.set(key, value)
return clone
})
}
const unset = (key: K) => {
setState((prev) => {
const clone = new Map(prev)
clone.delete(key)
return clone
})
}
const clear = () => {
setState((prev) => {
const clone = new Map(prev)
clone.clear()
return clone
})
}
return [state, { set, unset, clear }]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment