Computing Derived Data

Reselect is a simple library for creating memoized, composable selector functions. Reselect selectors can be used to efficiently compute derived data from the Redux store.

Motivation for Memoized Selectors

Let's revisit the Todos List example:

containers/VisibleTodoList.js

  1. import { connect } from 'react-redux'
  2. import { toggleTodo } from '../actions'
  3. import TodoList from '../components/TodoList'
  4. const getVisibleTodos = (todos, filter) => {
  5. switch (filter) {
  6. case 'SHOW_ALL':
  7. return todos
  8. case 'SHOW_COMPLETED':
  9. return todos.filter(t => t.completed)
  10. case 'SHOW_ACTIVE':
  11. return todos.filter(t => !t.completed)
  12. }
  13. }
  14. const mapStateToProps = state => {
  15. return {
  16. todos: getVisibleTodos(state.todos, state.visibilityFilter)
  17. }
  18. }
  19. const mapDispatchToProps = dispatch => {
  20. return {
  21. onTodoClick: id => {
  22. dispatch(toggleTodo(id))
  23. }
  24. }
  25. }
  26. const VisibleTodoList = connect(
  27. mapStateToProps,
  28. mapDispatchToProps
  29. )(TodoList)
  30. export default VisibleTodoList

In the above example, mapStateToProps calls getVisibleTodos to calculate todos. This works great, but there is a drawback: todos is calculated every time the component is updated. If the state tree is large, or the calculation expensive, repeating the calculation on every update may cause performance problems. Reselect can help to avoid these unnecessary recalculations.

Creating a Memoized Selector

We would like to replace getVisibleTodos with a memoized selector that recalculates todos when the value of state.todos or state.visibilityFilter changes, but not when changes occur in other (unrelated) parts of the state tree.

Reselect provides a function createSelector for creating memoized selectors. createSelector takes an array of input-selectors and a transform function as its arguments. If the Redux state tree is changed in a way that causes the value of an input-selector to change, the selector will call its transform function with the values of the input-selectors as arguments and return the result. If the values of the input-selectors are the same as the previous call to the selector, it will return the previously computed value instead of calling the transform function.

Let's define a memoized selector named getVisibleTodos to replace the non-memoized version above:

selectors/index.js

  1. import { createSelector } from 'reselect'
  2. const getVisibilityFilter = state => state.visibilityFilter
  3. const getTodos = state => state.todos
  4. export const getVisibleTodos = createSelector(
  5. [getVisibilityFilter, getTodos],
  6. (visibilityFilter, todos) => {
  7. switch (visibilityFilter) {
  8. case 'SHOW_ALL':
  9. return todos
  10. case 'SHOW_COMPLETED':
  11. return todos.filter(t => t.completed)
  12. case 'SHOW_ACTIVE':
  13. return todos.filter(t => !t.completed)
  14. }
  15. }
  16. )

In the example above, getVisibilityFilter and getTodos are input-selectors. They are created as ordinary non-memoized selector functions because they do not transform the data they select. getVisibleTodos on the other hand is a memoized selector. It takes getVisibilityFilter and getTodos as input-selectors, and a transform function that calculates the filtered todos list.

Composing Selectors

A memoized selector can itself be an input-selector to another memoized selector. Here is getVisibleTodos being used as an input-selector to a selector that further filters the todos by keyword:

  1. const getKeyword = state => state.keyword
  2. const getVisibleTodosFilteredByKeyword = createSelector(
  3. [getVisibleTodos, getKeyword],
  4. (visibleTodos, keyword) =>
  5. visibleTodos.filter(todo => todo.text.indexOf(keyword) > -1)
  6. )

Connecting a Selector to the Redux Store

If you are using React Redux, you can call selectors as regular functions inside mapStateToProps():

containers/VisibleTodoList.js

  1. import { connect } from 'react-redux'
  2. import { toggleTodo } from '../actions'
  3. import TodoList from '../components/TodoList'
  4. import { getVisibleTodos } from '../selectors'
  5. const mapStateToProps = state => {
  6. return {
  7. todos: getVisibleTodos(state)
  8. }
  9. }
  10. const mapDispatchToProps = dispatch => {
  11. return {
  12. onTodoClick: id => {
  13. dispatch(toggleTodo(id))
  14. }
  15. }
  16. }
  17. const VisibleTodoList = connect(
  18. mapStateToProps,
  19. mapDispatchToProps
  20. )(TodoList)
  21. export default VisibleTodoList

Accessing React Props in Selectors

So far we have only seen selectors receive the Redux store state as an argument, but a selector can receive props too.

For this example, we're going to extend our app to handle multiple Todo lists. Our state needs to be refactored so that it holds multiple todo lists, which each have their own todos and visibilityFilter state.

We also need to refactor our reducers. Now that todos and visibilityFilter live within every list's state, we only need one todoLists reducer to manage our state.

reducers/index.js

  1. import { combineReducers } from 'redux'
  2. import todoLists from './todoLists'
  3. export default combineReducers({
  4. todoLists
  5. })

reducers/todoLists.js

  1. // Note that we're hard coding three lists here just as an example.
  2. // In the real world, we'd have a feature to add/remove lists,
  3. // and this would be empty initially.
  4. const initialState = {
  5. 1: {
  6. todos: [],
  7. visibilityFilter: 'SHOW_ALL'
  8. },
  9. 2: {
  10. todos: [],
  11. visibilityFilter: 'SHOW_ALL'
  12. },
  13. 3: {
  14. todos: [],
  15. visibilityFilter: 'SHOW_ALL'
  16. }
  17. }
  18. const addTodo = (state, action) => {
  19. const todoList = state[action.listId]
  20. const { todos } = todoList
  21. return {
  22. ...state,
  23. [action.listId]: {
  24. ...todoList,
  25. todos: [
  26. ...todos,
  27. {
  28. id: action.id,
  29. text: action.text,
  30. completed: false
  31. }
  32. ]
  33. }
  34. }
  35. }
  36. const toggleTodo = (state, action) => {
  37. const todoList = state[action.listId]
  38. const { todos } = todoList
  39. return {
  40. ...state,
  41. [action.listId]: {
  42. ...todoList,
  43. todos: todos.map(todo =>
  44. (todo.id === action.id)
  45. ? {...todo, completed: !todo.completed}
  46. : todo
  47. )
  48. }
  49. }
  50. }
  51. const setVisibilityFilter = (state, action) => {
  52. const todoList = state[action.listId]
  53. return {
  54. ...state,
  55. [action.listId]: {
  56. ...todoList,
  57. visibilityFilter: action.filter
  58. }
  59. }
  60. }
  61. export default const todoLists = (state = initialState, action) => {
  62. // make sure a list with the given id exists
  63. if (!state[action.listId]) {
  64. return state;
  65. }
  66. switch (action.type) {
  67. case 'ADD_TODO':
  68. return addTodo(state, action)
  69. case 'TOGGLE_TODO':
  70. return toggleTodo(state, action)
  71. case 'SET_VISIBILITY_FILTER':
  72. return setVisibilityFilter(state, action)
  73. default:
  74. return state
  75. }
  76. }

The todoLists reducer now handles all three actions. The action creators will now need to be passed a listId:

actions/index.js

  1. let nextTodoId = 0
  2. export const addTodo = (text, listId) => ({
  3. type: 'ADD_TODO',
  4. id: nextTodoId++,
  5. text,
  6. listId
  7. })
  8. export const setVisibilityFilter = (filter, listId) => ({
  9. type: 'SET_VISIBILITY_FILTER',
  10. filter,
  11. listId
  12. })
  13. export const toggleTodo = (id, listId) => ({
  14. type: 'TOGGLE_TODO',
  15. id,
  16. listId
  17. })
  18. export const VisibilityFilters = {
  19. SHOW_ALL: 'SHOW_ALL',
  20. SHOW_COMPLETED: 'SHOW_COMPLETED',
  21. SHOW_ACTIVE: 'SHOW_ACTIVE'
  22. }

components/TodoList.js

  1. import React from 'react'
  2. import PropTypes from 'prop-types'
  3. import Todo from './Todo'
  4. const TodoList = ({ todos, toggleTodo, listId }) => (
  5. <ul>
  6. {todos.map(todo => (
  7. <Todo
  8. key={todo.id}
  9. {...todo}
  10. onClick={() => toggleTodo(todo.id, listId)}
  11. />
  12. ))}
  13. </ul>
  14. )
  15. export default TodoList

Here is an App component that renders three VisibleTodoList components, each of which has a listId prop:

components/App.js

  1. import React from 'react'
  2. import VisibleTodoList from '../containers/VisibleTodoList'
  3. const App = () => (
  4. <div>
  5. <VisibleTodoList listId="1" />
  6. <VisibleTodoList listId="2" />
  7. <VisibleTodoList listId="3" />
  8. </div>
  9. )

Each VisibleTodoList container should select a different slice of the state depending on the value of the listId prop, so we'll modify getVisibilityFilter and getTodos to accept a props argument.

selectors/todoSelectors.js

  1. import { createSelector } from 'reselect'
  2. const getVisibilityFilter = (state, props) =>
  3. state.todoLists[props.listId].visibilityFilter
  4. const getTodos = (state, props) => state.todoLists[props.listId].todos
  5. const getVisibleTodos = createSelector(
  6. [getVisibilityFilter, getTodos],
  7. (visibilityFilter, todos) => {
  8. switch (visibilityFilter) {
  9. case 'SHOW_COMPLETED':
  10. return todos.filter(todo => todo.completed)
  11. case 'SHOW_ACTIVE':
  12. return todos.filter(todo => !todo.completed)
  13. default:
  14. return todos
  15. }
  16. }
  17. )
  18. export default getVisibleTodos

props can be passed to getVisibleTodos from mapStateToProps:

  1. const mapStateToProps = (state, props) => {
  2. return {
  3. todos: getVisibleTodos(state, props)
  4. }
  5. }

So now getVisibleTodos has access to props, and everything seems to be working fine.

But there is a problem!

Using the getVisibleTodos selector with multiple instances of the visibleTodoList container will not correctly memoize:

containers/VisibleTodoList.js

  1. import { connect } from 'react-redux'
  2. import { toggleTodo } from '../actions'
  3. import TodoList from '../components/TodoList'
  4. import { getVisibleTodos } from '../selectors'
  5. const mapStateToProps = (state, props) => {
  6. return {
  7. // WARNING: THE FOLLOWING SELECTOR DOES NOT CORRECTLY MEMOIZE
  8. todos: getVisibleTodos(state, props)
  9. }
  10. }
  11. const mapDispatchToProps = dispatch => {
  12. return {
  13. onTodoClick: id => {
  14. dispatch(toggleTodo(id))
  15. }
  16. }
  17. }
  18. const VisibleTodoList = connect(
  19. mapStateToProps,
  20. mapDispatchToProps
  21. )(TodoList)
  22. export default VisibleTodoList

A selector created with createSelector only returns the cached value when its set of arguments is the same as its previous set of arguments. If we alternate between rendering <VisibleTodoList listId="1" /> and <VisibleTodoList listId="2" />, the shared selector will alternate between receiving {listId: 1} and {listId: 2} as its props argument. This will cause the arguments to be different on each call, so the selector will always recompute instead of returning the cached value. We'll see how to overcome this limitation in the next section.

Sharing Selectors Across Multiple Components

The examples in this section require React Redux v4.3.0 or greater

In order to share a selector across multiple VisibleTodoList components and retain memoization, each instance of the component needs its own private copy of the selector.

Let's create a function named makeGetVisibleTodos that returns a new copy of the getVisibleTodos selector each time it is called:

selectors/todoSelectors.js

  1. import { createSelector } from 'reselect'
  2. const getVisibilityFilter = (state, props) =>
  3. state.todoLists[props.listId].visibilityFilter
  4. const getTodos = (state, props) => state.todoLists[props.listId].todos
  5. const makeGetVisibleTodos = () => {
  6. return createSelector(
  7. [getVisibilityFilter, getTodos],
  8. (visibilityFilter, todos) => {
  9. switch (visibilityFilter) {
  10. case 'SHOW_COMPLETED':
  11. return todos.filter(todo => todo.completed)
  12. case 'SHOW_ACTIVE':
  13. return todos.filter(todo => !todo.completed)
  14. default:
  15. return todos
  16. }
  17. }
  18. )
  19. }
  20. export default makeGetVisibleTodos

We also need a way to give each instance of a container access to its own private selector. The mapStateToProps argument of connect can help with this.

If the mapStateToProps argument supplied to connect returns a function instead of an object, it will be used to create an individual mapStateToProps function for each instance of the container.

In the example below makeMapStateToProps creates a new getVisibleTodos selector, and returns a mapStateToProps function that has exclusive access to the new selector:

  1. const makeMapStateToProps = () => {
  2. const getVisibleTodos = makeGetVisibleTodos()
  3. const mapStateToProps = (state, props) => {
  4. return {
  5. todos: getVisibleTodos(state, props)
  6. }
  7. }
  8. return mapStateToProps
  9. }

If we pass makeMapStateToProps to connect, each instance of the VisibleTodosList container will get its own mapStateToProps function with a private getVisibleTodos selector. Memoization will now work correctly regardless of the render order of the VisibleTodoList containers.

containers/VisibleTodoList.js

  1. import { connect } from 'react-redux'
  2. import { toggleTodo } from '../actions'
  3. import TodoList from '../components/TodoList'
  4. import { makeGetVisibleTodos } from '../selectors'
  5. const makeMapStateToProps = () => {
  6. const getVisibleTodos = makeGetVisibleTodos()
  7. const mapStateToProps = (state, props) => {
  8. return {
  9. todos: getVisibleTodos(state, props)
  10. }
  11. }
  12. return mapStateToProps
  13. }
  14. const mapDispatchToProps = dispatch => {
  15. return {
  16. onTodoClick: id => {
  17. dispatch(toggleTodo(id))
  18. }
  19. }
  20. }
  21. const VisibleTodoList = connect(
  22. makeMapStateToProps,
  23. mapDispatchToProps
  24. )(TodoList)
  25. export default VisibleTodoList

Next Steps

Check out the official documentation of Reselect as well as its FAQ. Most Redux projects start using Reselect when they have performance problems because of too many derived computations and wasted re-renders, so make sure you are familiar with it before you build something big. It can also be useful to study its source code so you don't think it's magic.