///// function 내에서 /////
// count = 0; 대신
const [count, setCount] = React.useState(0);
setCount(1);
// (객체 나타내려면) state = {count: 0}; 대신
const [state,setState] = React.useState({count: 0});
setState({count: 1});
// 객체는 아래와 같이 변경도 가능
setState(state => {
return {
count: state.count+1
};
});
// 1) 항상 render된 직후 전부 실행
// (componentDidMount & componentDidUpdate 양쪽일때 모두)
React.useEffect( () => {
/* .. */
});
// 2) 최초 render 후에만 실행
// (두 번째 인자인 배열 안의 값이 변화될 때만 실행되므로)
React.useEffect( () => {
/* .. */
}, []);
// +) useEffect의 return 함수는 다음 번 실행 시 호출됨
// 2번째 실행은 1번째 실행의 return문과 함께
// 3번째 실행은 2번째 실행의 return문과 함께
// -> componentWillUnmount와 비슷한 역할
React.useEffect( () => {
/* .. */
return () => {
// cleanup(전 실행의 상태를 정리)
}
}, [count]);
⭐ useState는 state 대체 / useEffect는 라이프 사이클 훅(componentDidMount, componentDidUpdate, componentWillUnmount) 대체