import React, { useCallback, useMemo, useState } from "react";
const getAverage = (num) => {
console.log("average 실행중");
if (num.length === 0) return 0;
const sum = num.reduce((a, b) => a + b);
return sum / num.length;
};
export const Average = () => {
const [list, setList] = useState([]);
const [number, setNumber] = useState("");
const onChange = useCallback((e) => {
setNumber(e.target.value);
},[]);
const onInsert = useCallback((e) => {
const nextList = list.concat(parseInt(number));
setList(nextList);
setNumber("");
},[number, list]);
const avg = useMemo(() => getAverage(list), [list]);
return (
<div>
<input value={number} onChange={onChange} />
<button onClick={onInsert}>등록</button>
{list.map((value, index) => (
<p key={index}>{value}</p>
))}
<div>평균:{avg}</div>
</div>
);
};
함수 내부에서 상태값에 의존할 때 반드시 두 번째 인자에 배열을 포함해야함
useCallback(()=>{
console.log('hi');
}, []);
useMemo(()=>{
const foo = () => {
console.log('hi')
}
return foo;
}, [])