Hook이 등장하기 전까지는 클래스 컴포넌트가 국룰이어서 예전 React는 대부분 class로 작성이 되었다. Hook 형태로 작성된 함수 컴포넌트와 클래스 컴포넌트 둘 다 사용된다.
일반적인 function component는 다음과 같다.
function App() {
return
<div>
<h1>Hello</h1>
</div>
}
// 화살표 함수형을 더 많이 쓴다.
const DetailPresenter = ({ result, error, loading }) => (
<Container>
<Backdrop></Backdrop>
</Container>
);
class component는 다음과 같다.
return이 아니라 render 메소드 안에 return이 들어간다.
class App extends React.Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
// state를 constructor 내부에 쓰면 this.state의 형태로 적어준다
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
result: null,
error: null,
loading: true,
};
}
render () {
return null
}
}
왜 class component를 쓸까?
state를 쓸 수 있기 때문이다!
(그러나 이제 Hook의 등장으로 함수에서도 useState Hook을 통해 사용할 수 있게 되었다)
class App extends React.Component {
state = {
count: 0
};
render() {
return <h1>Count: {this.state.count}</h1>;
}
}
// constructor 내부에 state를 호출한다면 this.state로 정의해야 한다.
// class 컴포넌트 내부의 함수에서 state를 사용할 때는 this.state.[변수명]으로 사용함
state는 동적으로 움직이는 정보이다. 활용해보자!
class App extends React.Component {
state = {
count: 0
};
plus = () => {
this.setState({ count: this.state.count + 1 });
};
minus = () => {
this.setState({ count: this.state.count - 1 });
};
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.plus}>Plus</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
}
🚨 setState 메소드를 쓸 때마다 React는 state를 새로고침하고 render를 다시 렌더링할 것이다.
정확히는, state 값이 바뀌면 해당 state를 가지고 있는 컴포넌트의 render 함수가 재실행되고 그에 따라 render 함수 하위에 있는 컴포넌트의 render 함수도 재실행된다.