...기존 코드
// count를 초기화해주는 함수
const initCount = () => {
setCount(0)
}
...기존 코드
return (
...기존 코드
<Box1 initCount={initCount} />
...기존 코드
)
}
export default App
📁 components / Box1
import React from 'react'
const style = {
width: '100px',
height: '100px',
backgroundColor: '#01c49f',
color: "white"
}
function Box1({ initCount }) {
console.log('Box1 컴포넌트가 렌더링 되었습니다')
return (
<div style={style}>
<button
onClick={() => {
initCount();
}}>초기화</button>
</div>
)
}
export default React.memo(Box1)

+,- 버튼을 누르면 Box1이 리렌더링된다.function App() )initCount함수는 새로운 주소 값을 갖게 된다.Box1은 props가 바뀌었구나! 하고 인식하여 리렌더링이 된다.📁 App.jsx
// 변경 전
const initCount = () => {
setCount(0)
}
//변경 후
const initCount = useCallback(() => {
setCount(0)
},[])

const initCount = useCallback(() => {
console.log(`${count}에서 0으로 변경 되었습니다.`)
setCount(0)
},[])

${count}가 0으로 나오는 이유App컴포넌트가 그려질 때. 즉, 처음 initCount가 메모리에 저장 되었을때는 count가 0이었다.initCount가 새로 저장되는것이 아니므로 처음 저장 된 값 그대로 갖는다initCount도 갱신되어야하므로 const initCount = useCallback(() => {
console.log(`${count}에서 0으로 변경 되었습니다.`)
setCount(0)
},[count])

지금 결과는 맨 위에서 했던거랑 같은 결과 아닌가..?