Arrays and Objects cause unnecessary re-renders with Redux and Immutable.js












1















In my React project I have Redux state that is shaped something like this:



{
items: [{ ... }, { ... }, { ... }, ...]
form: {
searchField: '',
filter1: '',
filter2: '',
}
}


On one page there is a form component and list of items component. I am using Immutable.js, so a brand new items array is created whenever a form field is updated. Because the array reference is now different, this causes the list of items to be re-rendered even though the data within the array is the same.



Within my list component I am using componentDidUpdate to console log changes in state to confirm that the updated array is triggering the re-render:



componentDidUpdate(prevProps) {
Object.keys(prevProps).forEach((key) => {
if (prevProps[key] !== this.props[key]) {
console.log('changed prop:', key, 'from', this.props[key], 'to', prevProps[key]);
}
});
}


The from and to arrays that get logged contain all the exact same data.



How can I prevent these unnecessary re-renders?



The only thing I can think of is, within the shouldComponentUpdate of the list component, loop over the array and compare the item IDs with nextProps. However, this seems inefficient.



Here is my reducer



import Immutable from 'immutable';
import { types } from '../actions';

const initialState = {
items:
form: {
searchField: '',
filter1: '',
filter2: '',
}
}

export default function reducer(_state = initialState, action) {
const state = Immutable.fromJS(_state);

switch (action.type) {
case types.HANDLE_FORM_CHANGE:
return state.setIn(['form', action.field], action.value).toJS();
default:
return _state;
}
}









share|improve this question

























  • could you share your redux reducer? this looks like you could have an issue there.

    – Nikita Malyschkin
    Jan 17 at 23:08











  • Usually this isn't something that you prevent within the redux cycle. Sometimes a restructure of the data structure that holds the data is neccessary, but that isn't the solution you should jump straight to. Show us your components that are related to this data

    – Andrew
    Jan 17 at 23:24


















1















In my React project I have Redux state that is shaped something like this:



{
items: [{ ... }, { ... }, { ... }, ...]
form: {
searchField: '',
filter1: '',
filter2: '',
}
}


On one page there is a form component and list of items component. I am using Immutable.js, so a brand new items array is created whenever a form field is updated. Because the array reference is now different, this causes the list of items to be re-rendered even though the data within the array is the same.



Within my list component I am using componentDidUpdate to console log changes in state to confirm that the updated array is triggering the re-render:



componentDidUpdate(prevProps) {
Object.keys(prevProps).forEach((key) => {
if (prevProps[key] !== this.props[key]) {
console.log('changed prop:', key, 'from', this.props[key], 'to', prevProps[key]);
}
});
}


The from and to arrays that get logged contain all the exact same data.



How can I prevent these unnecessary re-renders?



The only thing I can think of is, within the shouldComponentUpdate of the list component, loop over the array and compare the item IDs with nextProps. However, this seems inefficient.



Here is my reducer



import Immutable from 'immutable';
import { types } from '../actions';

const initialState = {
items:
form: {
searchField: '',
filter1: '',
filter2: '',
}
}

export default function reducer(_state = initialState, action) {
const state = Immutable.fromJS(_state);

switch (action.type) {
case types.HANDLE_FORM_CHANGE:
return state.setIn(['form', action.field], action.value).toJS();
default:
return _state;
}
}









share|improve this question

























  • could you share your redux reducer? this looks like you could have an issue there.

    – Nikita Malyschkin
    Jan 17 at 23:08











  • Usually this isn't something that you prevent within the redux cycle. Sometimes a restructure of the data structure that holds the data is neccessary, but that isn't the solution you should jump straight to. Show us your components that are related to this data

    – Andrew
    Jan 17 at 23:24
















1












1








1


1






In my React project I have Redux state that is shaped something like this:



{
items: [{ ... }, { ... }, { ... }, ...]
form: {
searchField: '',
filter1: '',
filter2: '',
}
}


On one page there is a form component and list of items component. I am using Immutable.js, so a brand new items array is created whenever a form field is updated. Because the array reference is now different, this causes the list of items to be re-rendered even though the data within the array is the same.



Within my list component I am using componentDidUpdate to console log changes in state to confirm that the updated array is triggering the re-render:



componentDidUpdate(prevProps) {
Object.keys(prevProps).forEach((key) => {
if (prevProps[key] !== this.props[key]) {
console.log('changed prop:', key, 'from', this.props[key], 'to', prevProps[key]);
}
});
}


The from and to arrays that get logged contain all the exact same data.



How can I prevent these unnecessary re-renders?



The only thing I can think of is, within the shouldComponentUpdate of the list component, loop over the array and compare the item IDs with nextProps. However, this seems inefficient.



Here is my reducer



import Immutable from 'immutable';
import { types } from '../actions';

const initialState = {
items:
form: {
searchField: '',
filter1: '',
filter2: '',
}
}

export default function reducer(_state = initialState, action) {
const state = Immutable.fromJS(_state);

switch (action.type) {
case types.HANDLE_FORM_CHANGE:
return state.setIn(['form', action.field], action.value).toJS();
default:
return _state;
}
}









share|improve this question
















In my React project I have Redux state that is shaped something like this:



{
items: [{ ... }, { ... }, { ... }, ...]
form: {
searchField: '',
filter1: '',
filter2: '',
}
}


On one page there is a form component and list of items component. I am using Immutable.js, so a brand new items array is created whenever a form field is updated. Because the array reference is now different, this causes the list of items to be re-rendered even though the data within the array is the same.



Within my list component I am using componentDidUpdate to console log changes in state to confirm that the updated array is triggering the re-render:



componentDidUpdate(prevProps) {
Object.keys(prevProps).forEach((key) => {
if (prevProps[key] !== this.props[key]) {
console.log('changed prop:', key, 'from', this.props[key], 'to', prevProps[key]);
}
});
}


The from and to arrays that get logged contain all the exact same data.



How can I prevent these unnecessary re-renders?



The only thing I can think of is, within the shouldComponentUpdate of the list component, loop over the array and compare the item IDs with nextProps. However, this seems inefficient.



Here is my reducer



import Immutable from 'immutable';
import { types } from '../actions';

const initialState = {
items:
form: {
searchField: '',
filter1: '',
filter2: '',
}
}

export default function reducer(_state = initialState, action) {
const state = Immutable.fromJS(_state);

switch (action.type) {
case types.HANDLE_FORM_CHANGE:
return state.setIn(['form', action.field], action.value).toJS();
default:
return _state;
}
}






javascript reactjs redux react-redux immutable.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 18 at 15:58







plmok61

















asked Jan 17 at 23:01









plmok61plmok61

8011821




8011821













  • could you share your redux reducer? this looks like you could have an issue there.

    – Nikita Malyschkin
    Jan 17 at 23:08











  • Usually this isn't something that you prevent within the redux cycle. Sometimes a restructure of the data structure that holds the data is neccessary, but that isn't the solution you should jump straight to. Show us your components that are related to this data

    – Andrew
    Jan 17 at 23:24





















  • could you share your redux reducer? this looks like you could have an issue there.

    – Nikita Malyschkin
    Jan 17 at 23:08











  • Usually this isn't something that you prevent within the redux cycle. Sometimes a restructure of the data structure that holds the data is neccessary, but that isn't the solution you should jump straight to. Show us your components that are related to this data

    – Andrew
    Jan 17 at 23:24



















could you share your redux reducer? this looks like you could have an issue there.

– Nikita Malyschkin
Jan 17 at 23:08





could you share your redux reducer? this looks like you could have an issue there.

– Nikita Malyschkin
Jan 17 at 23:08













Usually this isn't something that you prevent within the redux cycle. Sometimes a restructure of the data structure that holds the data is neccessary, but that isn't the solution you should jump straight to. Show us your components that are related to this data

– Andrew
Jan 17 at 23:24







Usually this isn't something that you prevent within the redux cycle. Sometimes a restructure of the data structure that holds the data is neccessary, but that isn't the solution you should jump straight to. Show us your components that are related to this data

– Andrew
Jan 17 at 23:24














1 Answer
1






active

oldest

votes


















0














The shouldComponentUpdate approach is the way I've handled this / seen others handle this.



Note that you don't need to manually loop over your collection and compare ids as Immutable includes an is method for comparing collections:




Value equality check with semantics similar to Object.is, but treats
Immutable Collections as values, equal if the second Collection
includes equivalent values.




Obviously this assumes the state passed to your components are Immutable objects which I understand to be considered something of a best practice (see use immutable everywhere except your dumb components).






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54245523%2farrays-and-objects-cause-unnecessary-re-renders-with-redux-and-immutable-js%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The shouldComponentUpdate approach is the way I've handled this / seen others handle this.



    Note that you don't need to manually loop over your collection and compare ids as Immutable includes an is method for comparing collections:




    Value equality check with semantics similar to Object.is, but treats
    Immutable Collections as values, equal if the second Collection
    includes equivalent values.




    Obviously this assumes the state passed to your components are Immutable objects which I understand to be considered something of a best practice (see use immutable everywhere except your dumb components).






    share|improve this answer






























      0














      The shouldComponentUpdate approach is the way I've handled this / seen others handle this.



      Note that you don't need to manually loop over your collection and compare ids as Immutable includes an is method for comparing collections:




      Value equality check with semantics similar to Object.is, but treats
      Immutable Collections as values, equal if the second Collection
      includes equivalent values.




      Obviously this assumes the state passed to your components are Immutable objects which I understand to be considered something of a best practice (see use immutable everywhere except your dumb components).






      share|improve this answer




























        0












        0








        0







        The shouldComponentUpdate approach is the way I've handled this / seen others handle this.



        Note that you don't need to manually loop over your collection and compare ids as Immutable includes an is method for comparing collections:




        Value equality check with semantics similar to Object.is, but treats
        Immutable Collections as values, equal if the second Collection
        includes equivalent values.




        Obviously this assumes the state passed to your components are Immutable objects which I understand to be considered something of a best practice (see use immutable everywhere except your dumb components).






        share|improve this answer















        The shouldComponentUpdate approach is the way I've handled this / seen others handle this.



        Note that you don't need to manually loop over your collection and compare ids as Immutable includes an is method for comparing collections:




        Value equality check with semantics similar to Object.is, but treats
        Immutable Collections as values, equal if the second Collection
        includes equivalent values.




        Obviously this assumes the state passed to your components are Immutable objects which I understand to be considered something of a best practice (see use immutable everywhere except your dumb components).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 18 at 15:58

























        answered Jan 18 at 15:37









        net.uk.sweetnet.uk.sweet

        11.8k21936




        11.8k21936






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54245523%2farrays-and-objects-cause-unnecessary-re-renders-with-redux-and-immutable-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown