This section uses parts of the code created in previous tutorial parts.
Selectors without arguments
Selectors allows us to perform some expensive calculations and reuse results multiple times.
Let's say we want to calculate count of finished todos on our list.
Example without selectors
This will work just fine, but it is possible that we'll want to use result of the same calculation in another place.
Let's say we want to get remainig todos as well.
As you might see, in both 2 above cases, we will compute list of completed tasks each time todo list is changed.
Create first selector
Let's try to solve this problem by introducing selector.
And now use this selector value in 2 code examples we've written above:
To read selector value, call
selector.value instead of
Our code got a lot shorter and also calculation of how many tasks are completed will always happen only once after todos list update.
If selector reads any value from the store - it will automatically re-calculate it's value if such store value changes.
Selectors with arguments
Quite often we need to provide some additional input to the selector. Selector families are created for exactly this use case.
Let's create selector that returns todos by their status. Note now we'll return list of requested todos instead of count of them.
Now, we can start using such selector family like:
Selectors are used the same way in
watch reactions and
Selectors are caching their values, so calling
Will trigger selector function to be called only once.
Selectors are caching their value until any store (or other selector) value they use changes.
Any selector family can accept multiple arguments
In example above, we're again checking status of every single todo. Let's reuse selector we've created previously:
Arguments must be serializable
Arguments passed to selectors must be serializable. You can pass any set of arguments that is JSON like - plain objects, arrays, primitives like strings, numbers etc.
Such selector is incorrect and will throw, when called with function as an argument.