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