useMemo provides Redux
P粉845862826
P粉845862826 2023-08-25 21:04:43
0
2
631
<p>I'm new to Redux and I'd like to maximize the performance of my web application. </p> <p>I have a state in redux that I store in a variable to display later. </p> <p>This is the code: </p> <pre class="brush:php;toolbar:false;">constmetricsState = useSelector((state: MetricsStateObject) => state.MetricsState); const myMetrics =metricState.myMetrics;</pre> <p>I found that useMemo improves performance by not re-rendering if the data has not changed. </p> <p>So I'm wondering if <code>const myMetrics = useMemo(() =>metricsState.myMetrics, [metricsState.myMetrics]);</code> is a good practice, or is it completely useless? </p> <p>Thank you for your time. </p>
P粉845862826
P粉845862826

reply all(2)
P粉146080556

Let’s talk about the conclusion first, it’s completely useless.

Why? Because metricsState.myMetrics is just a value process and does not involve expensive calculations.

But useMemo itself consumes a certain amount of calculation.

So I think this is premature optimization

P粉726133917

useMemo Use for expensive calculations where you don't want to run every render. like

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

or something similar. You only evaluate this variable when megaBigArray changes.

In your case, the code will run on every render anyway, but useSelector should only trigger the render when the part of the store you selected changes. So you should be able to get by just fine without it.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!