useMemo with Redux

2.3k Views Asked by At

I'm new with Redux, and I'd like to improve performances of my web app as much as possible.

I have a state in redux, that I store in a variable to display it later.

Here is the code :

const metricsState = useSelector((state: MetricsStateObject) => state.MetricsState);
const myMetrics = metricsState.myMetrics;

I saw that useMemo improve performance by not re-render if the data did not mutate.

So I'm wondering if const myMetrics = useMemo(() => metricsState.myMetrics, [metricsState.myMetrics]); is a good practice, or totaly useless ?

Thank you for your time.

3

There are 3 best solutions below

1
Wraithy On BEST ANSWER

useMemo is for high cost computation, you dont want to run each render. Like

const something = useMemo(()=> megaBigArray.reduce((acc,i)=>acc*i,0), [megaBigArray])

or something like that. You only calculate that variable, if megaBigArraychange.

In your case, that code will be run every render anyways, but useSelector should trigger render only, when part of store you are selecting change. So you should be good without it.

1
Alvin On

Let me talk about the conclusion first, it's totally useless.

why? because metricsState.myMetrics is just a value-taking process and does not involve expensive calculations.

but useMemo itself consumes a certain amount of calculation.

so I think that belongs to premature optimization

2
Doge Fromage On

I think @Wraithys answer is not correct here. I'm pretty sure, React will not compute the component with the useSelector if the state of the selector didn't change and the selector also didn't change. This means that you must memoize the selector too, otherwise React and Redux will not be able to optimize the rendering. I think you may have to also memoize the component using React.memo() for it to work fully. Also, it may be best to always state your selectors in a file so you don't have to memoize them, since they are constant.