Blog>
Snippets

Performance Optimized Selector Use

Demonstrate the usage of reselect library for creating memoized selectors to optimize state selection and reduce unnecessary renders in renderer processes.
import { createSelector } from 'reselect';

// Assume we have a state shape like this:
// {
//   shop: {
//     items: [],
//     isLoading: false,
//     error: null
//   }
// }

// First, define a simple selector to retrieve the relevant slice of state.
const selectShopItems = state => state.shop.items;

// Then, create a memoized selector using createSelector from reselect.
// This selector will only recompute when the `items` slice of state actually changes,
// preventing unnecessary re-renders if the result is the same.
const selectExpensiveItems = createSelector(
  [selectShopItems],
  (items) => items.filter(item => item.price > 1000)
);

// Usage example of the memoized selector within a React component.
// In this scenario, only when the shop items change will `ExpensiveItemsComponent` re-render.
// connect is from react-redux, which binds the Redux store with the React component.
import { connect } from 'react-redux';

const ExpensiveItemsComponent = ({ expensiveItems }) => (
  // Component that renders expensive items
  <div>{/* Render expensive items here. */}</div>
);

const mapStateToProps = state => ({
  expensiveItems: selectExpensiveItems(state)
});

// Connect the component to the Redux store using the mapStateToProps with the memoized selector.
export default connect(mapStateToProps)(ExpensiveItemsComponent);
This example defines a memoized selector to compute expensive items from 'shop.items' using the 'reselect' library. It demonstrates how to optimize a React component's connection to the Redux store by re-rendering only when the specific slice of state changes, rather than on every state change, by utilizing createSelector.