How to create memoized selectors using Reselect library.
Selectors are an essential part of a Redux application, allowing you to extract, transform, and compute derived data from the Redux store. The Reselect library provides a simple way to create memoized selectors, which can improve performance by avoiding unnecessary recalculations. This article covers the following topics:
1. Description.
Reselect is a simple library for creating memoized, composable selector functions. Memoization is a technique used to speed up expensive calculations by storing the results of function calls and returning the cached result when the same inputs occur again. In a Redux application, selectors can be used to compute derived state, and with Reselect, these selectors are memoized to enhance performance.
Prerequisites :
Before diving into the coding steps, ensure you have the following prerequisites:
Folder Structure:
my-app/
├── node_modules/
├── public/
│ ├── index.html
│ └── ...
├── src/
│
│ │ └── App.js
│ ├── store/
│ │ ├── actions.js
│ │ ├── reducers.js
│ │ ├── selectors.js
│ │ └── store.js
│ ├── styles/
│ │ └── App.css
│ ├── index.js
│ └── ...
├── .gitignore
├── package.json
├── README.md
└── ...
Output:
2. All Possible Approaches (Syntax).
Reselect provides several ways to create memoized selectors. The most common approaches are:
The createSelector function takes input-selectors and an output-selector. Input-selectors are functions that extract specific slices of state, and the output-selector computes the derived state.
import { createSelector } from 'reselect';
const inputSelector = state => state.someSlice;
const memoizedSelector = createSelector(
[inputSelector],
(someSlice) => {
// Compute derived state
return someSlice.transformedData;
}
);
3. Describe Each Approach One by One.
Using createSelector
This is the most common approach and is suitable for most use cases.
Input selectors are simple functions that take the Redux state and return a part of it.
const getItems = (state) => state.items;
const getFilter = (state) => state.filter;
2. Define the Output Selector:
The output selector takes the results of the input selectors and computes the derived state.
import { createSelector } from 'reselect';
export const getFilteredItems = createSelector(
[getItems, getFilter],
(items, filter) => items.filter(item => item.type === filter)
);
Composing Multiple Selectors
You can also compose multiple selectors to create more complex derived state.
const getVisibleItems = createSelector(
[getItems, getFilter],
(items, filter) => items.filter(item => item.visible && item.type === filter)
);
const getVisibleItemNames = createSelector(
[getVisibleItems],
(visibleItems) => visibleItems.map(item => item.name)
);
4. Steps to Create Application (Install Required Modules) .
To create a React application that uses Reselect, follow these steps:
Recommended by LinkedIn
1. Install Create-React-App:
npx create-react-app my-app
cd my-app
Output
:
2. Install Redux, React-Redux, and Reselect:
npm install redux react-redux reselect
Output :
5. Updated Dependencies in package.json File.
Your package.json should include the following dependencies:
{
"dependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-redux": "^8.0.0",
"redux": "^4.0.0",
"reselect": "^4.0.0",
}
}
Output.
6. Example.
Here's a complete example of a React application using Reselect.
1. Redux Store Setup:
// Write this code in store.js file
import { createStore } from 'redux';
const initialState = {
items: [
{ id: 1, type: 'fruit', name: 'Apple' },
{ id: 2, type: 'vegetable', name: 'Carrot' },
{ id: 3, type: 'fruit', name: 'Banana' }
],
filter: 'fruit'
};
function rootReducer(state = initialState, action) {
return state;
}
const store = createStore(rootReducer);
export default store;
2.Selectors:
JavaScript
// Write this code in selectors.js
import { createSelector } from 'reselect';
const getItems = (state) => state.items;
const getFilter = (state) => state.filter;
export const getFilteredItems = createSelector(
[getItems, getFilter],
(items, filter) => items.filter(item => item.type === filter)
);
3. React Component:
JavaScript
//App.js
import React from 'react';
import { useSelector } from 'react-redux';
import { getFilteredItems } from './selectors';
function App() {
const filteredItems = useSelector(getFilteredItems);
return (
<div>
<h1>Filtered Items</h1>
<ul>
{filteredItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default App;
4. Connecting Redux Store to React:
JavaScript
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
7. Output .
You can download this project from my github.Github Project Link