stackjlei stackjlei - 1 year ago 98
React JSX Question

why does redux need to make a copy of the data each time it changes?

From what I've read, redux uses

or the spread operator to make a shallow copy of the data, but how does that make sense? I thought the whole point of it was to make a deep copy of the data that is dispatched so that if the data is changed outside the store, it won't change what's in the store also. if it were a shallow copy, then the data would be linked, which causes issues with the data changing what's in the store even without a dispatch, correct?

In the example below, if were only shallowly copied, then if that data were changed from wherever it came from, it would change what's in the store, even without the dispatch right?

const activePokemon = (state = {}, action) => {
switch (action.type) {
return {
return state

Answer Source

If you are following the Three Principles of redux, then you won't worry about changes outside the store.

The only way to change the state is to emit an action, an object describing what happened.

If the changes outside the store are intended to modify the state, dispatch should be used instead. In addition to update of the state, dispatch also notifies every subscriber of the store about the changes.

And once you 'linked' some data to the state, the data should not be changed, since it is a part of the state, and..

State is read-only

Edit: about making a copy

In the documentation of reducers(read it again for details!), redux only requires our reducers to stay pure. If the new state is different, the reducer must create new object, and making a copy is a way to describe the unchanged part.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download