DEV Community

Cover image for React.memo and useMemo
G Gokul
G Gokul

Posted on

React.memo and useMemo

React.memo:

  • React.memo is a performance optimization tool in React that prevents a functional component from re-rendering if its props have not changed.

How It works:

  • When a parent component attempts to update, React.memo performs a shallow comparison (Object.is) on the component's previous props and its new props:
  • If props are identical: React skips re-rendering the component entirely, saving processing power.
  • If props have changed: React proceeds with the re-render to reflect the new data.

Syntax Example:

import { memo } from 'react';

const MyComponent = memo(({ title, description }) => {
  console.log("Component rendered!");
  return (
    <div>
      <h3>{title}</h3>
      <p>{description}</p>
    </div>
  );
});

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

When Should You Use It?

  • You should not wrap every single component in memo because the comparison logic itself has a minor performance cost.
  • It is best used when:

  • The component is pure: It always renders the same output given the exact same props.

  • The component re-renders frequently: It is forced to re-render constantly because its parent component updates often.

  • The component is heavy: It contains a large UI tree or carries out expensive UI layout processes.

Difference between React.memo vs useMemo:

on

useMemo:

  • useMemo is a React Hook that caches (memoizes) the result of a calculation between re-renders.
  • By using the official React useMemo Hook, you optimize performance by ensuring that expensive, resource-heavy calculations only run when their specific inputs change, rather than on every single render.

How It Works (The Syntax):

useMemo accepts two arguments:

  1. a calculation function
  2. an array of dependencies.
import React, { useMemo } from 'react';

const memoizedValue = useMemo(() => {
  // 1. Perform expensive calculation here
  return someExpensiveCalculation(a, b);
}, [a, b]); // 2. Only re-run if 'a' or 'b' changes
Enter fullscreen mode Exit fullscreen mode

First Argument: A function that takes no arguments and returns the value you want to cache.
Second Argument: A dependency array containing all reactive values (props, state, or variables) used inside the function.

Use Cases:

  • Skipping expensive recalculations
  • Skipping re-rendering of child components
  • Memoizing a dependency for another Hook

Difference between useMemo vs useCallback vs React.memo:

i

Top comments (0)