Skip to content

How to manage native mutable data structures inside of atoms? #2708

Answered by dai-shi
marcebdev asked this question in Q&A
Discussion options

You must be logged in to vote

Mutable data structure doesn't follow the React contract, and it may behave weirdly with Concurrent React.

That being said, what we can do with atoms is to create a version. The idea is similar to atomWithRefresh.

const internalSetAtom = atomWithLazy({
  set: new Set(),
  version: 0,
});
const mySetAtom = atom(
  (get) => get(internalSetAtom).set,
  (get, set, action: SetAction) => {
    const current = get(internalSetAtom)
    if (action.type === 'add') {
      current.set.add(action.value)
      set({ ...current, version: current.version + 1 })
    } else if (action.type === 'remove') {
      current.set.delete(action.value)
      set({ ...current, version: current.version + 1 })
    }
  }

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by marcebdev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants