乐闻世界logo
搜索文章和话题

What are selectors in redux

4个答案

1
2
3
4

Selectors in Redux are functions used to extract and derive data from the Redux state tree. In Redux applications, the global state is stored as a single object. Since this state tree can be very large and contain numerous distinct data fragments, directly accessing the data can be both cumbersome and time-consuming. Selectors exist to simplify accessing data from the state tree.

Selectors' primary responsibilities and roles include:

  1. Abstract state structure: Selectors provide an abstraction layer that allows components to read state without needing to know the specific structure of the state tree. This means that if the state tree structure changes, only the relevant selectors need updating, without requiring modifications to all components that use this part of the state.

  2. Compute derived data: Selectors can be used to compute derived data, which involves generating new data representations based on raw data in the state tree. For example, filtering objects from an array of multiple objects that meet specific conditions, or calculating the sum of certain data.

  3. Optimize performance: With libraries like Reselect, selectors can avoid unnecessary computations through memoization techniques. This means the selector only re-computes when its inputs (i.e., the relevant parts of the state tree) change; otherwise, it returns the result from the previous computation, thereby improving application performance.

  4. Ensure reusability and composition: Selectors can be reused across different components and combined to build more complex selectors, which helps reduce code redundancy and maintain logical consistency.

Example

Suppose we have a Redux state that includes a product list, where each product has a price and a category. If we want to retrieve the total price of all electronic category products, we can write a selector to achieve this:

javascript
// state structure example const state = { products: [ { id: 1, name: 'mobile phone', category: 'electronics', price: 599 }, { id: 2, name: 'tablet', category: 'electronics', price: 799 }, { id: 3, name: 'watch', category: 'accessories', price: 199 } // more products... ] }; // Selector const selectElectronicProductsTotalPrice = (state) => { return state.products .filter(product => product.category === 'electronics') .reduce((total, product) => total + product.price, 0); }; // Use Selector const totalPrice = selectElectronicProductsTotalPrice(state); console.log(totalPrice); // Output should be 1398

In this example, selectElectronicProductsTotalPrice is a selector that first filters out all products in the electronic category and then calculates and returns the sum of their prices. This approach not only encapsulates the query logic for the state tree but also makes this logic easier to test and reuse.

2024年6月29日 12:07 回复

Selectors are functions that accept the Redux state as an argument and return data to be passed to components.

javascript
const getUserData = state => state.user.data;

Why use them?

  1. One primary reason is to avoid duplicate data in the Redux store.
  2. As the application grows, the shape of data objects changes, so avoid modifying it in all related components. It's recommended to change it in one place for easier maintenance.
  3. Selectors should be defined near the reducer because they operate on the same state, making data synchronization easier.

Using reselect helps memoize data, meaning it returns the previously computed result when the same input is passed to the function instead of recalculating. This enhances application performance.

2024年6月29日 12:07 回复

Selectors are functions that retrieve Redux state. Similar to getters, they encapsulate the state structure and are reusable. Additionally, selectors can compute derived properties.

You can write selectors, such as those used in Redux Saga. For example:

javascript
const getUsersNumber = ({ users }) => users.length; const getUsersIds = ({ users }) => users.map(({ id }) => id);

etc.

You can also use reselect, a simple selector library for Redux that memoizes selectors to improve efficiency.

2024年6月29日 12:07 回复

getUser is not a reducer; it is indeed a selector, which is a function that extracts specific data chunks from the store.

Selectors provide an extra layer so that if you change the store structure and suddenly your users are no longer located at state.entities.users but at state.users.objects.entities (or something else), you only need to update the getUser selector, rather than every component that uses it in the application. You don't have to modify the old references.

This makes them particularly convenient when refactoring the Redux store.

2024年6月29日 12:07 回复

你的答案