DEV Community

Cover image for Solving React Problems: When to use UseMemo
Luis Mori Guerra
Luis Mori Guerra

Posted on

Solving React Problems: When to use UseMemo

I always see this question, and for some reason, it could be hard to find a good reason.

I can imagine if you are from Angular framework it can be a problem to find a similar concept or example.

Although, if you are from Vue.js, it can be easier to understand if you compare userMemo with a computed value.

React.js and Vue.js are oriented to functional programming styles and focused on reducing the number of render cycles.

In the case of React.js , you must execute setState in the old days before hooks, and now you must use useState. In that way, you can centralize and control when the render cycle job is executed

In Vue.js you can find a similar strategy. Vue.js provides reactive properties by implementing setter and getter under the hood. You can control when to re-render based on small changes. and this is how Vue.js can provide double-binding like angular

While Angular has a big problem, Angular is still rendering all the component trees and has a change detector that tries to intercept DOM events, but this gives it a poor performance and is hard to improve.

Let's go with some examples
react.js

const weekDaySelected = useMemo(() => {
    const { day, month, year } = props.selectedDay || {};
    return getDayLabel(day, month, year);
  }, [props.selectedDay]);

render (
 <CalendarHeaderDay day="sun" active={weekDaySelected === "Sun"} />
)
Enter fullscreen mode Exit fullscreen mode

In this example, weekDaySelected is a primitive variable , which depends of prop, and must be reactive at any change to
props.selectedDay and in this way also allow avoiding unneeded renders in the component

On the other side, we have Vue.js

<template>
  <CalendarHeaderDay day="sun" :active="weekDaySelected === 'Sun'" />
</template>
...
export default {
  props: {
    selectedDay: {
      type: Object
    }
  },
 computed: {
    weekDaySelected() {
      const { day, month, year } = this.selectedDay || {};
      return getDayLabel(day, month, year);
    }
  },

Enter fullscreen mode Exit fullscreen mode

In the case of Vue.js while you define new properties in the computed: {} section, this will intercept any change in the variables you are using into the method, in this case, weekDaySelected for free.

Memoize values are one of the most important strategies to have in mind for Frontend developers due to modifying DOM being very expensive.

More examples are coming ...

Top comments (0)