// Example
const selectAndCompute = (state) => {/*expensive computation*/};
const MyComponent = (props) => {
const computedData = useSelector(selectAndCompute);
return '...';
}
useSelector
will prevent re-render of MyComponent
if the selectAndCompute
function computes the same result as last time it got triggered (and it gets triggered every time anything in redux state changes). But, this still requires selectAndCompute
to run and compute some result. This computation in itself might be expensive.
So, you can add reselect
's createSelector
to prevent even the computation done in the selectAndCompute
. For example if selectAndCompute
depends only on the part of the state state.transactions
you can define:
const selectAndCompute = createSelector(
[(state) => state.transactions],
(transactions) => {/*expensive computation*/}
);
Now, only if state.transactions
has changed the expensive computation will run, otherwise selectAndCompute
will immediately return the previous value. And finally useSelector
will then block the re-render, same as it would if reselect
was not used.
state.someKey
instances then you need to change your code in multiple places when you change the state. This looks trivial but what if your selectors implement complex business logic? Likeconst selectTotal = createSelector([selectPolicy,selectAge,selectPeriod,...],calculate)
– Few