Ad

Does Updating 1 Element In An Array Trigger A Render In React For Other Elements In Array?

- 1 answer

I am using React with Redux for my current project.

I have a state object like so:

state: {
    reducerOne: {
         keyOne: valueOne,
         keyTwo: valueTwo
    }
    reducerTwo: {
         keyThree: valueThree
         keyFour: valueFour
    }
}

Suppose valueFour is an array of objects. I use the valueFour array to map a bunch of React elements like so in the render method:

this.props.valueFour.map(()=> <div/>)

(Obviously the above is simplified but all that I am trying to indicate is that I am rendering a bunch of elements)

Now, I would like to update only 1 of the above elements. In my action/reducer code I return the entire valueFour array with the 1 element updated in a function like so:

action code

export function updateThingInArray(elementId){
    return (dispatch, getState) => {
        const myArray = getState().reducerTwo.keyFour
        for (let i=0; i < myArray.length; i++) {
           if (myArray[i].id === elementId){
               const result= [
                    ...myArray.slice(0,i),
                    Object.assign({},
                       myArray[i],
                       {field:newValue}),
                    ...myArray.slice(i+1)
               ]
               dispatch(update(result))
           }
        }
     }
}

reducer code:

export default handleActions({
  [UPDATE]: (state,{payload}) => Object.assign({},state, {keyFour: payload})
},{
  keyThree:{},
  keyFour:{}
})

(My reducer code uses the library redux-actions)

I hope all this makes sense. If it doesn't please ask and I will clarify.

But my question is, since keyFour has the entireArray technically updated, does that mean ALL my elements will update even though only 1 has new data? If so, is there a more efficient way of implementing what I am currently doing?

Ad

Answer

The render method will be called again, which means it will map through that array again. You can look at the elements tab in chrome and you can see the html that flashes, it is the part that changed. If the component has the same data and the same key, the actual html won't be changed, but the render method will be called in the children.

Edit: didn't realize you were updating a nested key, React only checks shallow equality: https://facebook.github.io/react/docs/shallow-compare.html

Ad
source: stackoverflow.com
Ad