import React, { useState } from "react";
const getAverage = (num) => {
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 = (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}>등록</button>
{list.map((value, index) => (
<p key={index}>{value}</p>
))}
<div>평균:{getAverage(list)}</div>
</div>
);
};
이 경우 숫자를 등록할 때뿐만 아니라 input의 값이 변경되어도(리렌더링) getAverage함수가 실행되면서 낭비됨.
import React, { 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 = (e) => {
setNumber(e.target.value);
};
const onInsert = (e) => {
const nextList = list.concat(parseInt(number));
setList(nextList);
setNumber("");
};
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>
);
};
deps 배열 내 값이 변경되면 우리가 등록한 함수를 호출해서 값을 연산(값이 변경되지 않았다면 이전 값 재사용)