Home  >  Q&A  >  body text

useMemo provides Redux

<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粉845862826P粉845862826443 days ago629

reply all(2)I'll reply

  • P粉146080556

    P粉1460805562023-08-26 16:13:29

    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

    reply
    0
  • P粉726133917

    P粉7261339172023-08-26 09:26:32

    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.

    reply
    0
  • Cancelreply