MENU
Memoizing a Value
Below, clicking the left button won't change the numbers but clicking the right button will. Rather unlike the case for useCallback() which always runs the callback when called, the callback passed to useMemo is not executed at all if the dependencies have not changed.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head><body>
<div></div>
<script type="text/babel">
function Example(){
const [a,setA] = React.useState(0);
const [b,setB] = React.useState(0);
const [c,setC] = React.useState(0);
const m = React.useMemo(
() => {
console.log(a,b,c);
return (a+b+c);
}, [b,c]
)
return (<React.Fragment>
<button onClick={()=>setA(a+1)}>{m}</button>
<button onClick={()=>setB(b+1)}>{b}</button>
</React.Fragment>);}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<Example/>);
</script>
</body></html>