import React, { memo, useCallback, useMemo, useReducer } from "react";
import personReducer from "./person-reducer";
export default function AppMentorsButton() {
const [person, dispatch] = useReducer(personReducer, initialPerson);
const handleUpdate = useCallback(() => {
const prev = prompt(`누구의 이름을 바꾸고 싶은가요?`);
const current = prompt(`이름을 무엇으로 바꾸고 싶은가요?`);
dispatch({ type: "updated", prev, current });
}, []);
const handleAdd = useCallback(() => {
const name = prompt(`멘토의 이름은?`);
const title = prompt(`멘토의 직함은?`);
dispatch({ type: "added", name, title });
}, []);
const handleDelete = useCallback(() => {
const name = prompt(`누구를 삭제하고 싶은가요?`);
dispatch({ type: "deleted", name });
}, []);
return (
<div>
<h1>{person.name}</h1>
<p>{person.name}의 앨범</p>
<ul>
{person.mentors.map((mentor, index) => (
<li key={index}>
{mentor.name} ({mentor.title})
</li>
))}
</ul>
<Button text="앨범 이름 변경" onClick={handleUpdate} />
<Button text="앨범 삭재" onClick={handleDelete} />
<Button text="앨범 추가" onClick={handleAdd} />
</div>
);
}
const Button = memo(({ text, onClick }) => {
const result = useMemo(() => calculateSomething(), []);
return (
<button
onClick={onClick}
style={{
backgroundColor: "black",
color: "white",
borderRadius: "20px",
margin: "0.4rem",
}}
>
{`${text} ${result}`}
</button>
);
});
function calculateSomething() {
let total = 0;
for (let i = 0; i < 10000; i++) {
total += i;
}
return total;
}
const initialPerson = {
name: "Kanye West",
mentors: [
{
name: "Ye",
title: "2018",
},
{
name: "Jesus Is King",
title: "2019",
},
],
};