useMemo is a React hook that lets you cache the result of a calculation between re-renders.
Call useMemo at the top level of your component to cache a calculation between re-renders.
During next renders, useMemo will either return an already stored value from the last render (if the dependencies haven’t changed), or call callback again, and return the result that callback
has returned.
Syntax
useMemo(callback, dependencies)
Example
import { useState, useMemo } from "react";
export default function UseMemoDemo() {
const [ data, setData ] = useState(1);
const [ memo, setMemo ] = useState(1);
console.log("Rendering component");
// run callback on memo change
const result = useMemo(() => {
console.log("Running useMemo callback: " + memo);
return new Date().getTime();
}, [ memo ]);
return (
<>
<div>Data: {data}</div>
<div>Memo: {memo}</div>
<p>{result}</p>
<button onClick={(() => setData(data + 1))}>Re-render component</button>
<button onClick={(() => setMemo(memo + 1))}>Run memo callback</button>
</>
);
}