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.useMemo
When to Use useMemo
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.Computations:
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.Stable References:
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, will only be recalculated when items changes, improving performance by avoiding unnecessary calculations on every render.sumItems
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) {...