For memoization/performance consideration, using useSelector with ShallowEqual
.
Will there be some more benefits for performance optimization using "Reselect/createSelector" option ?
Or both the options are same ?
Will have the data as JSON array objects at most of the selectors.
Before writing new selector , would like to consider performance/memoization benefits.
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With