Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useSelector and reselect , which one is performance beneficial

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.

like image 623
dsi Avatar asked Oct 15 '22 22:10

dsi


1 Answers

// 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.

like image 167
croraf Avatar answered Oct 18 '22 11:10

croraf