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

How to Use Error Boundaries to Handle Errors

## 1. Define an ErrorBoundary class component ``` class ErrorBoundary extends React.Component { //...

Custom Hook : Simplify Code with Reusable Logic

Setting up a reusable data-fetching function to simplify API calls and state management. # State In...