Functional Updates with Reselect 5.0
Demonstrate using Reselect 5.0 createSelector with functional updates to compute derived data when the state changes, showing performance improvements.
import { createSelector } from 'reselect';
Import the createSelector function from Reselect library.
// Assuming we have a state with users and posts
const selectUsers = state => state.users;
const selectPosts = state => state.posts;
Define simple selector functions for users and posts.
// Creates a memoized selector that calculates the number of posts per user
const selectPostsPerUser = createSelector(
[selectUsers, selectPosts],
(users, posts) => {
return users.map(user => ({
...user,
postCount: posts.filter(post => post.userId === user.id).length
}));
}
);
Create a memoized selector to compute the number of posts per user. It depends on users and posts selected from the state. It's a performance optimization to prevent unnecessary recalculations.
// This would be used within a component or with `mapStateToProps` in a connected component
// const mapStateToProps = state => ({
// usersWithPostCount: selectPostsPerUser(state)
// });
Example usage of the selector in a React component or with `mapStateToProps` for a Redux connected component.