Describe a scenario where using the Reselect library would significantly improve performance in a Redux application, and explain how it achieves this.

React JS interview question for Advanced practice.

Answer

A great scenario for Reselect is a to-do list application with a filter. Imagine you have thousands of to-do items in your Redux store and a filter to show only 'completed', 'active', or 'all' todos. Without Reselect, every time any part of the Redux state changes (even unrelated parts), a selector function to get the visible todos would have to re-filter the entire list of thousands of items. This is computationally expensive and can cause UI lag. Reselect solves this by creating memoized selectors. You would create input selectors to get the list of all todos and the current filter status. Then, you create a result selector that takes these inputs and performs the filtering. Reselect caches the result. If an action is dispatched that doesn't change the list of todos or the filter, the selector will not re-run the expensive filtering logic. Instead, it will instantly return the cached result, preventing unnecessary re-computation and re-rendering of the component.

Explanation

A selector created with Reselect will only recompute its value if the values of its input selectors change. If the inputs are the same as the last call, it will return the previously computed (memoized) value.

Related Questions