'does redux change the reference of rootState object when a field's value in a sub state changes?
i have my redux states setup like this
rootState
subState1
field1
field2
subState2
field1
field2
multiple sub states inside a root state. if i dispatch an action to change filed2 inside subState1, will redux change the entire rootState object(location of rootState in memory)? if it does so, it'll be performance intensive task. when i have a large store then it'll make no sense to use redux cuz on every change it'll replace the rootState object.
"dependencies": {
"@reduxjs/toolkit": "^1.8.1",
"react-redux": "^8.0.1",
}
Solution 1:[1]
Yes, the root state object is always replaced, because this is a fundamental principle of immutable updates: an immutable update requires copying every level of nesting down to the field that needs to be updated!
In other words, if I need to update state.a.b.c.d
, I have to write code like:
return {
...state,
a: {
...state.a,
b: {
..state.a.b,
c: {
...state.a.b.c,
d: newValue
}
}
}
}
However, I think you are seriously over-estimating the "performance" implications here. Sure, every JS operation has a cost, and that includes copying objects. However, copying the root state (ie, {...state}
) typically has almost no cost, because the cost of copying a single object is O(numFields)
. In other words, copying an object with 5 fields will be faster than copying an object with 50,000 fields... and a Redux root state object might typically have 5-20 top-level slices (ie, {users, posts, comments, todos, counter}
, etc).
Generally, reducers are not a perf bottleneck in a Redux app. Doesn't mean they're never a perf issue. But most of the time it's the cost of updating the UI that actually matters.
Also, per your comment about "wanting to know what's happening behind the scenes":
spoiler:
THERE ISN'T ANYTHING "BEHIND THE SCENES"! :)
Typically, all the logic that actually matters in the reducers is code that you wrote yourself. The only code in the redux
core lib that comes into play here is the combineReducers
function, and that's just doing the work to help copy and update the root state object.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | markerikson |