Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Redux, is it necessary to do deep copy

Tags:

reactjs

redux

The below object is action.data has a nested object address

{
    name: 'Ben',
    address: {
        country: 'Australia',
        state: 'NSW'
    }
}

How should I handle it in the reducer?

const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            return {...state, data: action.data}
    }
}

Can I do it as above? that I just assign the whole object to data without copying?

or

const rootReducer = (state = initState, action) {
    switch(action.type) {
        switch RECEIVE_DATA:
            const address = {...action.data.address}
            const data = {...action.data, address}
            return {...state, data}
    }
}

Or should I do a deep copy of the object and assign it to data? thanks

like image 434
Benjamin Li Avatar asked Apr 01 '17 00:04

Benjamin Li


2 Answers

The "correct" way to handle updates of nested data is with multiple shallow copies, one for each level of nesting. It's also certainly okay to create a new object that just replaces one field completely, per your first example.

See the Redux docs section on Immutable Update Patterns for some info on how to properly do immutable updates, and also the Redux FAQ entry regarding deep cloning.

like image 192
markerikson Avatar answered Nov 15 '22 08:11

markerikson


From Redux:

Common Redux misconception: you need to deeply clone the state. Reality: if something inside doesn't change, keep its reference the same!

like image 41
Emi Avatar answered Nov 15 '22 10:11

Emi