File size: 6,559 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
---
id: getting-started
title: Getting Started
sidebar_label: Getting Started
sidebar_position: 1
hide_title: true
description: 'Getting Started'
---
import { InternalLinks } from '@site/src/components/InternalLinks'
import { ExternalLinks } from '@site/src/components/ExternalLinks'
import PackageTabs from '@site/src/components/PackageManagerTabs'
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
import Link from '@docusaurus/Link'
# Getting Started with Reselect
A library for creating memoized "selector" functions. Commonly used with Redux, but usable with any plain JS immutable data as well.
- Selectors can compute derived data, allowing <ExternalLinks.Redux /> to store the minimal possible state.
- Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
- Selectors are composable. They can be used as input to other selectors.
The **Redux docs usage page on <Link to="https://redux.js.org/usage/deriving-data-selectors">Deriving Data with Selectors</Link>** covers the purpose and motivation for selectors, why memoized selectors are useful, typical Reselect usage patterns, and using selectors with <ExternalLinks.ReactRedux />.
## Installation
### Redux Toolkit
While Reselect is not exclusive to <ExternalLinks.Redux />, it is already included by default in <ExternalLinks.ReduxToolkit text='the official Redux Toolkit package' /> - no further installation needed.
```ts
import { createSelector } from '@reduxjs/toolkit'
```
### Standalone
For standalone usage, install the `reselect` package:
<PackageTabs />
---
## Basic Usage
Reselect exports a `createSelector` API, which generates memoized selector functions. `createSelector` accepts one or more input selectors, which extract values from arguments, and a result function that receives the extracted values and should return a derived value. If the generated output selector is called multiple times, the output will only be recalculated when the extracted values have changed.
You can play around with the following **example** in <Link to='https://codesandbox.io/s/reselect-example-g3k9gf?file=/src/index.js'>this CodeSandbox</Link>:
{/* START: basicUsage.ts */}
<Tabs
groupId='language'
defaultValue='ts'
values={[
{label: 'TypeScript', value: 'ts'},
{label: 'JavaScript', value: 'js'},
]}>
<TabItem value='ts'>
```ts title="basicUsage.ts"
import { createSelector } from 'reselect'
interface RootState {
todos: { id: number; completed: boolean }[]
alerts: { id: number; read: boolean }[]
}
const state: RootState = {
todos: [
{ id: 0, completed: false },
{ id: 1, completed: true }
],
alerts: [
{ id: 0, read: false },
{ id: 1, read: true }
]
}
const selectCompletedTodos = (state: RootState) => {
console.log('selector ran')
return state.todos.filter(todo => todo.completed === true)
}
selectCompletedTodos(state) // selector ran
selectCompletedTodos(state) // selector ran
selectCompletedTodos(state) // selector ran
const memoizedSelectCompletedTodos = createSelector(
[(state: RootState) => state.todos],
todos => {
console.log('memoized selector ran')
return todos.filter(todo => todo.completed === true)
}
)
memoizedSelectCompletedTodos(state) // memoized selector ran
memoizedSelectCompletedTodos(state)
memoizedSelectCompletedTodos(state)
console.log(selectCompletedTodos(state) === selectCompletedTodos(state)) //=> false
console.log(
memoizedSelectCompletedTodos(state) === memoizedSelectCompletedTodos(state)
) //=> true
```
</TabItem>
<TabItem value='js'>
```js title="basicUsage.js"
import { createSelector } from 'reselect'
const state = {
todos: [
{ id: 0, completed: false },
{ id: 1, completed: true }
],
alerts: [
{ id: 0, read: false },
{ id: 1, read: true }
]
}
const selectCompletedTodos = state => {
console.log('selector ran')
return state.todos.filter(todo => todo.completed === true)
}
selectCompletedTodos(state) // selector ran
selectCompletedTodos(state) // selector ran
selectCompletedTodos(state) // selector ran
const memoizedSelectCompletedTodos = createSelector(
[state => state.todos],
todos => {
console.log('memoized selector ran')
return todos.filter(todo => todo.completed === true)
}
)
memoizedSelectCompletedTodos(state) // memoized selector ran
memoizedSelectCompletedTodos(state)
memoizedSelectCompletedTodos(state)
console.log(selectCompletedTodos(state) === selectCompletedTodos(state)) //=> false
console.log(
memoizedSelectCompletedTodos(state) === memoizedSelectCompletedTodos(state)
) //=> true
```
</TabItem>
</Tabs>
{/* END: basicUsage.ts */}
As you can see from the example above, `memoizedSelectCompletedTodos` does not run the second or third time, but we still get the same return value as last time.
In addition to skipping unnecessary recalculations, `memoizedSelectCompletedTodos` returns the existing result reference if there is no recalculation. This is important for libraries like React-Redux or React that often rely on reference equality checks to optimize UI updates.
---
## Terminology
- <InternalLinks.Selector text={<b>Selector Function</b>} />
: A function that accepts one or more JavaScript values as arguments, and derives
a result. When used with <ExternalLinks.Redux />, the first argument is typically
the entire Redux store state.
- <InternalLinks.InputSelectors text={<b>Input Selectors</b>} />
: Basic selector functions used as building blocks for creating a memoized selector.
They are passed as the first argument(s) to <InternalLinks.CreateSelector />, and
are called with all selector arguments. They are responsible for extracting and
providing necessary values to the <InternalLinks.ResultFunction />.
- <InternalLinks.OutputSelector text={<b>Output Selector</b>} />
: The actual memoized selectors created by <InternalLinks.CreateSelector />.
- <InternalLinks.ResultFunction text={<b>Result Function</b>} />
: The function that comes after the <InternalLinks.InputSelectors />
. It takes the <InternalLinks.InputSelectors />' return values as arguments
and returns a result.
- <InternalLinks.Dependencies text={<b>Dependencies</b>} />
: Same as <InternalLinks.InputSelectors />
. They are what the <InternalLinks.OutputSelector /> "depends" on.
The below example serves as a visual aid:
```ts
const outputSelector = createSelector(
[inputSelector1, inputSelector2, inputSelector3], // synonymous with `dependencies`.
resultFunc // Result function
)
```
|