클래스형 컴포넌트에는 lifecyle 메서드라는 것이 존재한다.
컴포넌트 안에 어떤 변화가 있었을때, 처음에 로딩될때, 컴포넌트가 해체될때 등 함수나 코드를 실행할 수 있는 기능이다.
대표적으로 다음과 같은 메서드들이 존재한다.
componentDidUpdate : 컴포넌트가 업데이트될 때 실행
componentDidMount : 컴포넌트가 처음 로딩될 때 실행
componentWillUnmount : 컴포넌트가 해체되기 직전에 실행
import React, {Component} from 'react';
export default class App extends Component {
componentDidMount(){
//code this
}
componentDidUpdate(){
//code this
}
componentWillUnmount(){
//code this
}
render() {
return(
<div>
</div>
)
}
}
함수형 컴포넌트에는 이러한 lifecycle 메서드가 존재하지 않는다.
대신 useEffect라는 react hook을 lifecycle처럼 사용할 수 있다.
import { useState, useEffect } from 'react';
function App() {
const [state,setState] = useState();
useEffect(() => {
//code
}); //컴포넌트에 어떤 일이 일어나기만 하면 code를 실행
useEffect(() => {
//code
},[]); //컴포넌트가 로드될때 맨 처음 한번만 code를 실행. componentDidMount와 비슷
useEffect(() => {
//code
},[state]); //state라는 변수에 변화가 있을 경우에만 code를 실행. 변수는 여러가지가 들어갈 수도 있음
//componentDidUpdate와 비슷
useEffect(() => {
//code1
return () => {
//code2
}
//컴포넌트가 해체되기 직전에 return 안에 code2가 실행됨
//componentWillUnmount와 비슷
});
return (
<div>
</div>
)
}
'programming > React' 카테고리의 다른 글
클래스형 컴포넌트 vs 함수형 컴포넌트 (0) | 2021.08.02 |
---|---|
React. Create 구현 (0) | 2021.03.18 |
React. 이벤트 (0) | 2021.02.18 |
React. 컴포넌트 만들기, Props, state (0) | 2021.02.18 |
React. 리액트 입문 (1) | 2021.02.17 |