Skip to content

Is getMappedItems an anti-pattern in mapStateToProps? #1948

@pgilad

Description

@pgilad

In all real-world examples (including code we use in our own work) I see the following pattern emerging in mapStateToProps:

// action
export const getOrganizations = state => state.entities.organizations;

export const getMappedOrganizations = (state, ids) => {
    const { byId } = getOrganizations(state);
    return ids.map(id => byId[id]);
};

// view
const mapStateToProps = state => {
    const { byAll } = getOrganizations(state);
    const organizations = getMappedOrganizations(state, byAll.ids);

    return {
        isFetching: byAll.isFetching,
        lastUpdated: byAll.lastUpdated,
        organizations,
    };
};

This provides the view all the data it needs, but unfortunately organizations will always be a new array when store updates, resulting in redundant updates of the view even though nothing has changed.

This is especially noticed when you have a popup or modal that updates store as well, and the list in the background, resulting in slowness because the view is always updating.

Is this really the advised pattern? Should you modify shouldComponentUpdate to fit it for non-shallow comparison in this case? Perhaps you should pass down the functions to create the mapped items and do so in the render function instead?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions