Skip to content

Commit

Permalink
chap 8.4 add sample code for useMemo
Browse files Browse the repository at this point in the history
  • Loading branch information
ye-geeee committed Sep 6, 2021
1 parent 618f2f5 commit 5dc94f4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion basic/src/App.js
Expand Up @@ -10,6 +10,7 @@ import IterationSample from './IterationSample';
import LifeCycleSample from './LifeCycleSample';
import ErrorBoundary from './ErrorBoundary';
import Info from './Info';
import Average from './Average';

function getRandomColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
Expand All @@ -19,7 +20,7 @@ const App = () => {
const [visible, setVisible] = useState(false);

return (
<Info />
<Average />
);
};

Expand Down
40 changes: 40 additions & 0 deletions basic/src/Average.js
@@ -0,0 +1,40 @@
import React, { useState } from 'react';

const getAverage = numbers => {
console.log('Calculating average...');
if (numbers.length === 0) return 0;
const sum = numbers.reduce((a, b) => a + b);
return sum / numbers.length;
};

const Average = () => {
const [list, setList] = useState([]);
const [number, setNumber] = useState('');

const onChange = e => {
setNumber(e.target.value);
};

const onInsert = e => {
const nextList = list.concat(parseInt(number));
setList(nextList);
setNumber('');
};

return (
<div>
<input value={number} onChange={onChange} />
<button onClick={onInsert}>Insert</button>
<ul>
{list.map((value, index) => (
<li key={index}>{value}</li>
))}
</ul>
<div>
<b>Average:</b>{getAverage(list)}
</div>
</div>
);
};

export default Average;

0 comments on commit 5dc94f4

Please sign in to comment.