Ask Question

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?

Reacthooksmap

443 views

AuthorΒ΄s AnkiCodes image

AnkiCodes

Last edited on

1 Answer available

Best answer

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)));
  }

  // ...
}
πŸ‘
1