What is the difference between 'useMemo' and 'memo' in React?

Yobi Bina Setiawan
28 Jan 2025 ยท Frontend

In React, the difference between useMemo and memo lies in how and where they're used:

  1. useMemo:

    • useMemo is a hook that you can use inside a component to optimize expensive calculations. It memoizes the result of a computation and only recalculates it when the dependencies change.
    • Example use case: If you have a complex function that processes data or performs expensive calculations, useMemo ensures that it only runs again when the data it's dependent on changes.
    • Syntax:
      js
      const memoizedValue = useMemo(() => expensiveCalculation(input), [input]);
  2. memo:

    • memo is a higher-order component (HOC) that is used to memoize a whole component. It prevents unnecessary re-renders by checking if the component's props have changed. If the props are the same as the previous render, React skips the re-render for that component.
    • Example use case: If you have a component that doesn't need to re-render unless its props change, you can wrap it in memo to optimize performance.
    • Syntax:
      js
      const MyComponent = React.memo(function MyComponent(props) { // component logic });

Summary:

  • useMemo is for memoizing values within a component to optimize calculations.
  • memo is for memoizing components to prevent unnecessary re-renders.

Keep Healthy and Happy Coding! ๐Ÿ˜‰