Skip to content

Return previous state if the props change but not the output #441

@lukemcgregor

Description

@lukemcgregor

I have an array of posts, which is filtered by user such that I have the following

const currentUsersPosts = createSelector(
  [state => state.currentUser.id, state=> state.posts],
 (userId, posts) => posts.filter(p=>p.id === userId)
);

When a new post is creates for another user this correctly filters the list and produces an identical (but differently referenced) array. This means that I re-render the component needlessly. Is there a way to get at the previously memo'd value for this instance of the reselector and return that if it's shallow equal (hence avoiding children re-rendering)?

eg:

import { shallowEqualArrays } from 'shallow-equal';

const currentUsersPosts = createSelector(
  [state => state.currentUser.id, state=> state.posts],
 (userId, posts, prevPostsForUser) => {
     const nextPostsForUser = posts.filter(p=>p.id === userId);
     return shallowEqualArrays(prevPostsForUser, nextPostsForUser) 
        ? prevPostsForUser
         : nextPostsForUser;
  }
);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions