useMemo
- 숫자,문자열,객체 를 재사용 하기 위해 사용.
useCallback
import React, { useState, useMemo, useCallback, useRef } from "react"
const getAverage = (numbers) => {
console.log("getting 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 inputEl = useRef(null)
const onChange = useCallback((e) => {
setNumber(e.target.value)
}, []) //컴포넌트가 처음 렌더링될 때만 함수 생성
const onInsert = useCallback(
(e) => {
const nextList = list.concat(parseInt(number))
setList(nextList)
setNumber("")
inputEl.current.focus()
},
[number, list] // number 혹은 list가 바뀌었을때만 함수 생성
)
const avg = useMemo(() => getAverage(list), [list])
return (
<div>
<input value={number} onChange={onChange} ref={inputEl} />
<button onClick={onInsert}>Register</button>
<ul>
{list.map((value, index) => (
<li key={index}>{value}</li>
))}
</ul>
<div>
<strong>Average:</strong> {avg}
</div>
</div>
)
}
export default Average
조금 더 배우고 내용 더 추가해야겠다..오늘 처음 본것들이 너무 많다..😂