name
property of state. On the same page, another component renders data
. In order to render state data we create a selector in our state class:state
injected as their first argument. The above selector will be recalculated every time the user types into the input component. Since state
could update rapidly when a user types, the expensive selector will needlessly recalculate even though it does not care about the name
property of state
changing. This selector does not take advantage of memoization.injectContainerState
selector option at root, state, or selector level. By default (in NGXS v3), the state is implicitly injected as the first argument for composite selectors defined within state classes. Turning off this setting prevents the container state from being injected as the first argument. This requires you to explicitly specify all arguments when you use the @Selector([...])
decorator. Any parameterless @Selector()
decorators will still inject the state as an implicit argument. Note that this option does not apply to selectors declared outside of state classes (because there is no container state to inject). For example, we create two selectors in our state class:getViewData
selector will not be recalculated when a user types into the input component. This selector targets the specific property of state
it cares about as its argument by leveraging an additional selector. When the name
property of state changes, the getViewData
arguments do not change. Memoization is taken advantage of.id
as an argument and returns a boolean indicating whether or not this id
is selected. The lazy selector returned by isDataSelected
uses Array.includes and has O(n)
time complexity. In this example, we want to render a list of checkboxes:state.selectedIds
is updated, therefore the isDataSelected
selector is recalculated and the list must re-render. Every time the list re-renders, the lazy selector isDataSelected
is invoked data.length
number of times. Because the lazy selector implementation has O(n)
time complexity, this template renders with O(n^2)
time complexity - Ugh!. One magnitude of n
for the length of data
, another for state.selectedIds.length
.O(1)
time complexity, this template renders with O(n)
time complexity. This optimizes performance by a magnitude of n
.