1. 컴포넌트 내부 state 초기화
•
컴포넌트의 prop이 변경된다고 내부 state가 초기화 되는 것이 아니다. react는 같은 컴포넌트가 UI Tree 상 같은 위치에 존재할 경우 해당 컴포넌트의 내부 state를 보존한다.
•
UI Tree 상 위치가 변경 될 경우 내부 state가 파괴된다.
•
ProfilePage는 userId를 prop으로 받으며 유저에게 comment 입력을 state로 받고있다. 프로필을 이동하면 작성하던 comment가 사라지지 않고 그대로 남아있다.
잘못된 내부 state 초기화
export default function ProfilePage({ userId }) {
const [comment, setComment] = useState('');
// 🔴 Avoid: Resetting state on prop change in an Effect
useEffect(() => {
setComment('');
}, [userId]);
// ...
}
TypeScript
복사
•
이유 1. ProfilePage는 stale값으로 렌더한 후 다시 렌더링하기 때문에 effect를 이용해 내부 state를 파괴하는건 효율적이지 못하다.
•
이유 2. 내부 children 모두 내부 state를 변경해주는 effect를 추가해줘야 한다.
Key 활용
export default function ProfilePage({ userId }) {
return (
<Profile
userId={userId}
key={userId}
/>
);
}
function Profile({ userId }) {
// ✅ This and any other state below will reset on key change automatically
const [comment, setComment] = useState('');
// ...
}
TypeScript
복사
•
컴포넌트에 key가 제공될 경우 react는 전혀 다른 두개의 컴포넌트로 인식한다. → 전혀 다른 컴포넌트는 내부 state가 공유되어선 안되므로 key가 다른 컴포넌트가 생성될 경우 DOM을 다시 그리고 내부 state를 파괴하고 다시 만든다.