Using useMemo for Caching and Optimizing Performance


useMemo is a React Hook that helps optimize performance by memoizing (caching) the result of a function so that it doesn't need to be recalculated on every render.

When to Use useMemo

Computations: When you have a computation that’s expensive and its result doesn’t change often, you can use useMemo to avoid recalculating it on every render.

Stable References: When passing objects or arrays as props to child components, useMemo can help ensure that the references to these props remain stable, avoiding unnecessary re-renders of child components.

Example:

import React, { useMemo } from 'react';

function MyComponent({ items }) {
  // This computation will only be recalculated if `items` changes
  const sumItems = useMemo(() => {
    return items.reduce((sum, item) => sum + item.value, 0);
  }, [items]);

  return <div>Total Value: {sumItems}</div>;
}

In this example, sumItems will only be recalculated when items changes, improving performance by avoiding unnecessary calculations on every render.

You Might Also Like

Conditional Rendering with Short Circuit

if you don’t need the else block while rendering components in React Js, you can do like this ```...

Labels: Names used to label loops and control flow

``` outerLoop: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (j === 1) {...