Skip to content

Commit 82b04e2

Browse files
committed
total を useMemo フックでメモ化
1 parent d1b03eb commit 82b04e2

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/App.js

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState } from 'react';
1+
import { useMemo, useState } from 'react';
22

33
const App = () => {
44
console.log('renders <App />');
@@ -61,15 +61,17 @@ const AddButton = ({ disabled, onClick }) => {
6161
const Total = ({ cartItems }) => {
6262
console.log('renders <Total />');
6363

64-
const total = cartItems.reduce((acc, cur) => {
65-
const t = Date.now();
64+
const total = useMemo(() => {
65+
return cartItems.reduce((acc, cur) => {
66+
const t = Date.now();
6667

67-
while (Date.now() - t < 100) {
68-
// 擬似的に100ミリ秒の遅延を発生させる
69-
}
68+
while (Date.now() - t < 100) {
69+
// 擬似的に100ミリ秒の遅延を発生させる
70+
}
7071

71-
return cur.length * 100 + acc;
72-
}, 0);
72+
return cur.length * 100 + acc;
73+
}, 0);
74+
}, [cartItems]);
7375

7476
return <p>合計: {total}</p>;
7577
};

0 commit comments

Comments
 (0)