useMemo的使用

回到文章
<p>点击add1按钮,sum发生变化</p>
<p>点击set now time按钮,sum固定不变</p>
<p>sum只随着count变化,而跟其他的state无关</p>

<div id="app"></div>
#app {
  font-size: 30px;
}
#app button {
  font-size: 24px;
}
const { useState, useEffect, useMemo } = React;

const Home = () => {
  const [count, setCount] = useState(0);
  const [nowtime, setNowtime] = useState(0);
  const sum = useMemo(() => ((1 + count) * count) / 2 + " ,random: " + Math.random(), [count]);

  return (
    <>
      <p> count: {count}</p>
      <p> sum: {sum}</p>
      <p> nowtime: {nowtime}</p>
      <button onClick={() => setCount(count + 1)}> add 1 </button>
      <button onClick={() => setNowtime(Date.now())}> set now time </button>
    </>
  );
};
ReactDOM.render(<Home />, document.getElementById("app"));