React.memo()

`React.memo()` is a higher-order component (HOC) provided by React. It’s used to memoize the rendering of functional components based on their props. This means that React will re-render the component only if its props have changed since the last render.

Syntax of React.memo():

const MemoizedComponent = React.memo((props) => {
// Component logic here
});

When to use React.memo() over useMemo() & vice-versa ?

React provides us with powerful tools to optimize the performance of our applications. Two such tools are `React.memo()` and `useMemo()`, which serve similar yet distinct purposes.

In this article, we’ll explore when to use `React.memo()` over `useMemo()` and vice versa, along with syntax and code examples to illustrate their usage.

Table of Content

  • React.memo()
  • useMemo()
  • Choosing Between React.memo() and useMemo()
  • Example of React.memo() & useMemo

Similar Reads

React.memo():

`React.memo()` is a higher-order component (HOC) provided by React. It’s used to memoize the rendering of functional components based on their props. This means that React will re-render the component only if its props have changed since the last render....

useMemo():

`useMemo()` is a React hook used to memoize the result of expensive computations within functional components. It accepts a function and an array of dependencies. The result of the function is memoized until one of the dependencies changes....

Choosing Between React.memo() and useMemo():

Feature React.memo( ) useMemo( ) Purpose Used to memoize components. Used to memoize values. Usage Wraps a React component, preventing re-renders if props have not changed. Called inside a React component to memoize expensive calculations. Type of Memoization Shallow comparison of props by default, but can accept a custom comparison function. Memoizes any calculated value, including objects, arrays, and other data types. When to Use When a component frequently re-renders with the same props. To optimize performance by avoiding expensive calculations on every render. Scope At the component level for preventing re-renders. Inside a component to memoize specific values or computations. Example Use Case Memoizing a list item component in a large list to prevent unnecessary re-renders of all list items when one item changes. Memoizing the result of a filter or sort operation on a list to avoid recalculating the list on every render. Syntax Example React.memo(Component) const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);...

Example of React.memo() & useMemo:

Example: Below is the example of TodoList with React.memo() based on todos prop to prevent unnecessary re-renders. Use useMemo() for TodoItem to optimize completion status computation based on todo.completed, avoiding redundant recalculations....