How to use a HashMap with React state management?

I am working with a program that contains 1000s of user objects, and HashMaps are a must to keep performance in check. For example, the user needs to be able to click on an on-screen object and enter editing mode for that object in O(1) time.

Here is an example partial implementation I found created with Zustand:

import { create } from 'zustand'

export interface DataStorageInterface {
    UserObjectType1: Map<String, Object>
}

export const DataStorage = create<DataStorageInterface>(() => ({
    UserObjectType1: new Map<String, Object>()
}))

If a function was made for the store that can manipulate a hashmap within it, how can I signal to Zustand that the hashmap has changed and needs a re-render with all components that depend on it?

Re-creating the Hashmap completely, or putting it within an array, is not an option.

Is this possible with redux without creating a new Hashmap? I also want to subscribe some UI components exclusively to that hashmap.

\According to the docs: State has to be updated immutably, which basically means using Map probably isn’t going to work.

The alternate would be use to a Plain-ol-javascript-object (POJO), so {}.

import { create } from 'zustand'

export interface DataStorageInterface {
    UserObjectType1: Record<String, Object>
}

export const DataStorage = create<DataStorageInterface>(() => ({
    UserObjectType1: {}
}))

(Record is a TypeScript utility type that is comparable to {[key: string]: Object} in this case)

With this you can follow along with the docs on updating managing your hash-map, while keeping the performance gains. The one area where you lose out in Map vs {} is you aren’t guaranteed the order of the keys in the map, but that shouldn’t be an issue if you save the order in another piece of state (usually an array of ids)

The Zustand docs say you need to wrap them in an object and call setState.

I guess you can also use Immer with Zustand.


There are also useMap hooks you can use (or write yourself).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.