useMemo memoizes a calculated value in a functional component, reusing it across renders until its dependencies change. It can help avoid expensive recalculations when the inputs stay the same. section 7.3.1 section 7.0
A costly calculation
If an input contains a password and displaying its cryptographic hash is expensive, useMemo can avoid recalculating the hash when the password has not changed. section 7.3.1
Listing 4.17 Gallery v4 using functions (excerpt)
import { useMemo } from 'react'; #1
...
function Image({ index, title }) {
const id = useMemo(() => #2
`image-${Math.floor(Math.random() * 1000000)}`, #2
[]); #2
return (
<figure style={{ margin: "5px" }} id={id}>
<img src={`//picsum.photos/id/${index}/150/150/`} alt={title} />
<figcaption>
<h3>Species: {title}</h3>
</figcaption>
</figure>
);
}
...
A gallery image uses useMemo with an empty dependency array to generate an ID once and reuse it across renders. section 4.4.4


