Phil Mok
Phil Mok

Reputation: 4050

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

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;
  }
}

Upvotes: 1

Views: 709

Answers (1)

net.uk.sweet
net.uk.sweet

Reputation: 12431

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).

Upvotes: 1

Related Questions