<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

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js