Blog>
Snippets

Implementing Redux Selectors

Create a selector using createSelector from the Redux Toolkit to compute derived data from the Redux store efficiently.
import { createSelector } from '@reduxjs/toolkit';

// Example state shape
// const state = {
//     products: {
//         list: [{ id: 1, price: 10.99, category: 'fruits' }, { id: 2, price: 5.99, category: 'vegetables' }],
//         filter: 'fruits'
//     }
// };

// Selector to get product list from state
const selectProductList = state => state.products.list;

// Selector to get current filter from state
const selectProductFilter = state => state.products.filter;

// createSelector to compute filtered products based on the list and the current filter
const selectFilteredProducts = createSelector(
    [selectProductList, selectProductFilter],
    (productList, productFilter) => productList.filter(product => product.category === productFilter)
);

export default selectFilteredProducts;
This piece of code defines a Redux selector using the createSelector function from Redux Toolkit. It takes the list of products and the current filter from the state, and computes a new array of products that only includes those that match the filter category. It's efficient as createSelector memorizes the computed result and re-computes it only when the input selectors' outputs change.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redux Selector Example</title>
    <script src="./selector.js"></script>
</head>
<body>
    <!-- Your HTML content here -->
    <!-- The script here will use selectFilteredProducts to display filtered products -->
    <script>
        // Assume you have a Redux store named 'store'
        // You would use the selector like this:
        store.subscribe(() => {
            const filteredProducts = selectFilteredProducts(store.getState());
            // Render the filtered products to the UI
        });
    </script>
</body>
</html>
This piece of HTML code creates a basic webpage structure where you can render the filtered list of products. The JavaScript within script tags should be replaced with actual logic that connects to a Redux store, utilizes the `selectFilteredProducts` selector to get the relevant data, and then renders it to the user interface.
body {
    font-family: 'Arial', sans-serif;
}

/* Add some basic styles here if needed */
This is a basic CSS snippet that sets the default font for the body element of the webpage. Additional CSS styles can be added to style the UI elements that display the filtered list of products.