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" />
</>
)
}
const memoizedResult = useMemo(() => {
return expensiveFunction(propA, propB);
}, [propA, propB]);
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.
/*
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]);
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>
)
}
//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]);