컴포넌트 라이프사이클
💻 class 컴포넌트의 경우
- component, createRef, Router 를 사용하기 위해 import
import { Component, createRef } from "react";
import Router from "next/router";
- 타입스크립트이므로 count 에 number를 설정
interface IState {
count: number;
}
- Component 클래스형 컴포넌트라 옛방식들이다.
export default class ClassComponentLifecyclePage extends Component {
inputRef = createRef<HTMLInputElement>();
state = {
count: 0,
};
componentDidMount = () => {
console.log("컴포넌트 마운트 완료!!");
this.inputRef.current.focus();
};
componentDidUpdate = () => {
console.log("컴포넌트 수정 완료!!");
};
componentWillUnmount = () => {
console.log("잘가요~~");
};
onClickCount = () => {
this.setState((prev: IState) => ({
count: prev.count + 1,
}));
};
onClickMove = () => {
Router.push("/");
};
render() {
return (
<>
현재카운트 : {this.state.count}
<button onClick={this.onClickCount}>카운트 증가!!!</button>
<button onClick={this.onClickMove}> 페이지 이동하기 </button>
<input type="text" ref={this.inputRef} />
</>
);
}
}
💻 함수형 컴포넌트의 경우
- useEffect, useRef, useState, useRouter를 쓰기위해 import
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";
export default function FunctioanlComponentLifecyclePage() {
const router = useRouter();
const [count, setCount] = useState(0);
const inputRef = useRef<HTMLInputElement>();
return () => {
console.log("잘가요~~");
};
}, []);
useEffect(() => {
console.log("컴포넌트 수정 완료!!");
});
function onClickCount() {
setCount((prev) => prev + 1);
}
function onClickMove() {
router.push("/");
}
return (
<>
현재카운트 : {count}
<button onClick={onClickCount}>카운트증가!!</button>
<button onClick={onClickMove}>페이지이동</button>
<input type="text" ref={inputRef} />
</>
);
}