얼마전 완성한 리액트 프로젝트를 회고 하면서 다음 리액트 프로젝트를 시작 하기 전,
리액트를 깊이있게 공부하고 싶어 적는 나의 리액트 공부.log
Reactjs.org의 공식 문서 중 MAIN CONCEPTS 를 다시 한번 천천히 살펴보자.
리액트 Elements 는 불변성을 가진다.
출력된 화면을 변경하는 유일한 방법은 새로운 Element를 만들어
ReactDOM.render()에 전달하는 것 뿐이다.
리액트 공부를 깊이있게 하지 못한 것 같다.
아래 코드를 봐보자.
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);
위 예제 코드는 element를 1초마다 생성하여 ReactDOM.render()에 뿌려준다.
일반적으로 ReactDOM.render()는 한번만 호출되기 때문에
이렇게 하면 화면 전체를 rerendering 할줄 알았는데,
실제로는 새롭게 전달된 element와 이전 element를 비교하여 변경된 부분만 리렌더링한다.
아래는 reactjs.org에 나오는 내용이다.
React Only Updates What's Necessary
React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.
Even though we create an element describing the whole UI tree on every tick, only the text node whose contents have changed gets updated by React DOM.
내가 프로젝트 하면서 실수 했던 부분인데, 이번에 알게 되서 부끄럽다기분이 좋다.
//Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
//Correct
this.setState((state, props) => ({
counter: state.counter + props.increment,
}));
this.setState
에서 this.state
를 사용하지말고, argument로 state
와 props
를 받아와서 써야 한다. 이는 setState
가 비동기로 처리되기 때문에 경우에 따라 잘못된 결과가 나올 수도 있다.
콜백으로 호출된 메소드안에서 this
를 사용하기 위해선 bind를 해야 한다.
constructor(props){
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
이런게 귀찮다면
//public class field syntax
handleClick = () => {
console.log('this is: ',this);
}
/*또는*/
//바운드 할때 arrow function을 사용
<button onClick={() => this.handleClick()}> Click me </button>
이렇게 public class fields syntax를 사용하거나 arrow function을 사용하라고 나와있다.
하지만 arrow function
을 사용하는 방법은 추천하지 않는다. 이유는 버튼이 렌더링 될때마다 매번 다른 콜백이 생성되게 되는데 이는 콜백이 만약 하위 컴포넌트의 props
로 전달되는 경우, 불필요한 또다른 리렌더링을 하게 되기 때문이다.
결론 > 되도록 귀찮더라도 constructor에서 bind를 하자. public class field syntax
를 사용해도 되지만 이건 Experimental syntax라서 추천하지 않는 듯 하다.
하지만 arrow function이 편한걸 ㅠ