Engineering note · React Js

Using useMemo for Caching and Optimizing Performance

By Published Updated

React Js

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:

CODE SAMPLE Code snippet
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.

More engineering notes

Conditional Rendering with Short Circuit

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

Default Props for Components

This code sets a default value for the text prop in the Button component. If no text prop is provide...