ReactJS: How to work with Map in useState hook
I want to use useState(new Map())
in my react component. Since I want to store the state data in a key value pairs.
How can I work with a Map
in hooks and how to update it?
39263 views
π
2
I want to use useState(new Map())
in my react component. Since I want to store the state data in a key value pairs.
How can I work with a Map
in hooks and how to update it?
39263 views
You can of course use Map
as usual in a useState()
hook.
But you have to be careful if it comes to updating the map. Following code snippet should work for you π
const MapStateComponent = () => {
const [mapState, setMapState] = useState(new Map());
const updateMap = (key, value) => {
setMapState(map => new Map(map.set(key, value)));
}
// ...
}