해당글은 React공식문서를 바탕으로 쓰여진 것이며 그외에 참고한 문서는 따로 Reference를 쓰도록하겠다.
정의
함수 컴포넌트에서 React state와 lifecycle features을 "연동(hook into)"할 수 있게 해주는 함수
예제코드
state 변수 선언
클래스에서는 constructor안에서 this.state를 설정하고 초기화 했지만 함수 컴포넌트에서는 이게 불가능하기 때문에 useState
를 컴포넌트에 호출하여 State를 설정하고 초기화한다.
useState
this.state.count
와 this.setState
와 유사하다.import React, { useState } from 'react';
function ExampleWithManyStates() {
// 상태 변수를 여러 개 선언했습니다!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
/* 배열구조분해를 하지 않는다면 */
var fruitStateVariable = useState('banana');
var fruit = fruitStateVariable[0];
var setFruit = fruitStateVariable[1];
}
this.setState와 setState(setAge...)가 다른점
this.setState와 setState는 많은 부분이 같지만 state 갱신하는 방법이 다르다.
this.setState는 state를 병합하는 것이지만 setState는 대체하는 것이다.
useEffect
이다.Class 컴포넌트를 이용한 예시
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
render
메서드 자체로는 side effect를 발생시키지 않고 Dom을 업데이트하고 난 후에 effect를 수행한다.Hook을 사용한 예시
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Class 컴포넌트를 사용하는 예시
class FriendStatus extends React.Component {
constructor(props) {
super(props);
this.state = { isOnline: null };
this.handleStatusChange = this.handleStatusChange.bind(this);
}
componentDidMount() {
ChatAPI.subscribeToFriendStatus(
this.props.friend.id,
this.handleStatusChange
);
}
componentWillUnmount() {
ChatAPI.unsubscribeFromFriendStatus(
this.props.friend.id,
this.handleStatusChange
);
}
handleStatusChange(status) {
this.setState({
isOnline: status.isOnline
});
}
render() {
if (this.state.isOnline === null) {
return 'Loading...';
}
return this.state.isOnline ? 'Online' : 'Offline';
}
}
Hook을 사용하는 예시
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// effect 이후에 어떻게 정리(clean-up)할 것인지 표시한다.
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}