reactjsreduxreact-usememo

useMemo with Redux


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.


Solution

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