Responding to Events
Can event handlers have side effects?
Absolutely! Event handlers are the best place for side effects.
Unlike rendering functions, event handlers don’t need to be pure, so it’s a great place to change something—for example, change an input’s value in response to typing, or change a list in response to a button press. However, in order to change some information, you first need some way to store it. In React, this is done by using state, a component’s memory. You will learn all about it on the next page.
⇒ 요거 기억하자. 헷갈릴 수 있는 개념인듯.
State: A Component’s Memory
- hook is like import. 마치 파일의 맨 위에서 모듈을 import해서 사용하는 것처럼, 훅도 컴포넌트의 가장 top level에 불러와 놓고 사용한다고 생각하면 된다.
- challenge 3 ~ hook은 그리고 return 전에 위치시켜야 한다고 한다. 요건 또 몰랐네? top level에 있어야 하는건 알았는데.
- challenge 4 ~ 얘도 좋은 예제. useState이 필요 없는 경우.
- A state variable is only necessary to keep information between re-renders of a component. Within a single event handler, a regular variable will do fine. Don’t introduce state variables when a regular variable works well.
- 설명되어 있는 것처럼 state같은 경우에는 “렌더링이 다시 일어나는 상황”에서 값을 저장해놓고 싶은 경우에 사용해야 한다. 만약 렌더링이 다시 일어나지 않는 상황(예를들어 예제처럼 한 event handler안에서 변수를 사용하는 상황)이라면 state를 사용하는게 아니라 일반 JS 변수를 사용해 주어야 한다.
- 그리고 왜 setter가 작동하지 않는가~
- ⇒ 이유는 state as a snapshot에서 다룬다.
Queueing a Series of State Updates
queue.forEach(v => {
if(typeof v === 'function'){
finalState = v(finalState);
}else{
finalState = v
}
})
for (let update of queue) {
if (typeof update === 'function') {
// Apply the updater function.
finalState = update(finalState);
} else {
// Replace the next state.
finalState = update;
}
}
Updating Objects in State
- deep dive : Using a single event handler for multiple fields ⇒ [ ] 써서 property dynamic naming
- deep dive: Objects are not really nested ⇒ 실제로는 별개의 object를 pointing(참조하는) 하는 형태로 동작하는구나. 이것도 처음 알았네. 원리를 이해하는데 도움이 된다.
- deep dive: Why is mutating state not recommended in React? ⇒ 안읽어봤다. 함 읽어봐라.