Search code examples
redux

Is it safe to have multiple references to the same object within a redux store?


Imagine a store like this:

{
    data: [ object1, object2, object3 ],
    current: object2
}

store.current is supposed to point to the currently edited or selected object. I'm not duplicating object2, I'm simply pointing to the same object as data[2] is.

I've been told to avoid multiple references like this in the redux store, but didn't get an explanation. The suggestion was to use an an index (e.g. current: 2) or in more complex scenarios, a path to the actual object (e.g. current: 'data.2' above).

The actual use-case involves a tree data structure where the path could look something like current: 'data.2.children.8.children.2.children.18', requiring a traversal each time the currently selected object is needed in a component.

Is it safe to store a reference to this object in store.current, or are there pitfalls associated with doing that?


Solution

  • As for why this is probably not a good idea: every modification of your objects will require new copies - and if you have something referenced in three places, you not only have to create that copy, but also update all references to now point at that copy.

    You should be using a selector function instead of duplicating data (reference or not) or doing that traversal in your component.