useMemo provides Redux
P粉845862826
2023-08-25 21:04:43
<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>
Let’s talk about the conclusion first, it’s completely useless.
Why? BecausemetricsState.myMetrics
is just avalue
process and does not involve expensive calculations.But
useMemo
itself consumes a certain amount of calculation.So I think this is premature optimization
useMemo
Use for expensive calculations where you don't want to run every render. likeor 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.