top of page
Logo der Online Agentur mdwp

Reselect

Reselect is a library used in conjunction with React.js, especially when using Redux for state management. The main purpose of Reselect is to create selector functions that compute derived data from the Redux store. In simple terms, it helps us to extract and manipulate data from the store and supply this as props to React components.

One major benefit of using Reselect is its memorization feature. It means that selectors created using Reselect will not compute a new result unless the value of its input props change. This helps improve the performance, especially when dealing with large states, as it prevents unnecessary re-renderings.

Here is a basic usage of Reselect:

```javascript
import { createSelector } from 'reselect';

// Define input selectors. These extract data from the Redux state.
const getUsers = state => state.users;
const getPosts = state => state.posts;

// Create a memoized selector
const getActiveUserWithPosts = createSelector(
[getUsers, getPosts],
(users, posts) => {
// This function will only run when users or posts change.
const activeUser = users.activeUser;
return {
...activeUser,
posts: posts.filter(post => post.userId === activeUser.id)
};
}
);
```

In this code snippet, the selector `getActiveUserWithPosts` is created using `createSelector` from reselect. As its first argument, createSelector accepts an array of input selectors (`getUsers` and `getPosts`). Its second argument is a function that computes some derived data (active user with their associated posts) using the values returned by the input selectors.

React components can then use this selector to get the derived data from Redux state. Since `getActiveUserWithPosts` is memoized, the computing function will only run when either the users or posts change in the state. This means unnecessary re-renderings can be avoided as long as the input selectors return the same values.

bottom of page