<div id="app"></div>
import { useEffect, useState, useMemo } from "https://esm.sh/react";
import ReactDOM from "https://esm.sh/react-dom";
function WithUseMemoComponent ({ stock }) {
console.log('stock.fruits', stock)
return <>
<p>Without useMemo: </p>
<h2>{stock.fruits}</h2>
</>
}
function WithoutUseMemoComponent ({ stock }) {
return <>
<p>With useMemo: </p>
<h2>{stock.fruits}</h2>
</>
}
function App() {
const [stock, setStock] = useState({
fruits: 3
});
// const useMemoStock = {
// ...stock
// };
// Freezed data
const useMemoStock = useMemo(() => {
return stock
},[])
return (
<>
<p>When needs to cache complex computed data without computing each time when component rendered, useMemo is good option.</p>
<hr />
<WithUseMemoComponent stock={stock}/>
<WithoutUseMemoComponent stock={useMemoStock} />
<button onClick={() => setStock(prev => ({
prev,
fruits: prev.fruits +1
}))}>
add item
</button>
<button onClick={() => setStock(prev => ({
prev,
fruits: prev.fruits -1
}))}>
decrease item
</button>
</>)
}
ReactDOM.render(<App />, document.querySelector("#app"));
View Compiled
This Pen doesn't use any external CSS resources.