useMemo is a hook that takes a function and a list of dependencies as arguments, and returns a value that is the result of calling the function. The value is stored in a cache and is only re-computed if one of the dependencies has changed.
Here is the syntax for useMemo:
xxxxxxxxxx
import { useMemo } from 'react';
function MyComponent(props) {
// Calculate the value of `result` using an expensive computation
// The value will only be re-computed if `props.x` or `props.y` changes
const result = useMemo(() => {
// Perform the expensive computation here
let sum = 0;
for (let i = 0; i < props.x; i++) {
sum += i;
}
return sum;
}, [props.x, props.y]);
return (
<div>
The sum of the first {props.x} positive integers is {result}.
</div>
);
}
In this example, the component calculates the sum of the first props.x positive integers using an expensive loop. The value is stored in a cache and is only re-computed if either props.x or props.y changes. This can help to improve the performance of the component by avoiding unnecessary re-calculations.
xxxxxxxxxx
const memoizedResult = useMemo(() => {
return expensiveFunction(propA, propB);
}, [propA, propB]);
xxxxxxxxxx
import React, { memo, useMemo, useState } from 'react'
const Heading = memo(({ style, title }) => {
console.log('Rendered:', title)
return <h1 style={style}>{title}</h1>
})
export default function App() {
const [count, setCount] = useState(0)
const normalStyle = {
backgroundColor: 'teal',
color: 'white',
}
const memoizedStyle = useMemo(() => {
return {
backgroundColor: 'red',
color: 'white',
}
}, [])
return (
<>
<button
onClick={() => {
setCount(count + 1)
}}
>
Increment {count}
</button>
<Heading style={memoizedStyle} title="Memoized" />
<Heading style={normalStyle} title="Normal" />
</>
)
}
xxxxxxxxxx
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Returns a memoized value.
Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.
Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.
If no array is provided, a new value will be computed on every render.
You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.
xxxxxxxxxx
/*
Pass a “create” function and an array of dependencies.
useMemo will only recompute the memoized value when one
of the dependencies has changed. This optimization helps
to avoid expensive calculations on every render.
*/
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
xxxxxxxxxx
import React, { useEffect, useMemo } from "react"
import { massiveArray } from "./massiveArray"
export const filterAndMapMassiveArrayToNumber = number => {
// There are much better ways and algorithms to do this sorting,
// this is only for illustrating the purpose of useMemo.
return massiveArray
.map(item => ({
item,
value: item.value * myNumber,
}))
.filter(item => item.value > 10)
}
export default function UseMemoWithExpensiveFunctionExample({ myNumber = 1 }) {
const finishedArray = useMemo(
() => filterAndMapMassiveArrayToNumber(myNumber),
[myNumber]
)
return (
<ul>
{finishedArray.map(item => (
<li key={item.id}>{item.value}</li>
))}
</ul>
)
}
xxxxxxxxxx
//when just a or b dependency change memoizedValie is work
// we are doing for when your component rendering but this memorizedValue to complexity have
// and you just want to render this complexity codes when a or b changes
const memoizedValue = useMemo(() => {
return computeExpensiveValue(a, b)
}, [a, b]);