EffectHook
useEffect는 함수 컴포넌트내에서 이런 side effects를 수행할 수 있게 해줍니다.
React class의 componentDidMount나 componentDidUpdate, componentWillUnmount와
같은 목적을 제공하지만, 하나의 API로 통합되었습니다.
이를 통해 렌더링 이후의 작업, 상태 변화에 따른 동작, 컴포넌트 정리(clean-up) 등을 간결하게 구현할 수 있습니다.
componentDidMount처럼 동작합니다.
의존성 배열을 빈 배열([])로 설정하면, 컴포넌트가 처음 마운트될 때만 실행됩니다.
useEffect(() => {
}, [])
componentDidMount + componentDidUpdate처럼 동작합니다.
의존성 배열을 생략하면, 컴포넌트가 렌더링될 때마다 실행됩니다.
useEffect(() => {
})
componentDidMount + 특정 값이 변경되었을 떄에만 해당하는 componentDidUpdate처럼 동작합니다.
의존성 배열에 특정 값을 넣으면, 해당 값이 변경될 때만 실행됩니다.
useEffect(() => {
const [state, serstate] = useState(initialState);
}, [state,props.a]) // 의존성 배열
componentWillUnmount 처럼 동작합니다.
useEffect 내부에서 반환하는 함수는 컴포넌트가 언마운트되거나 의존성 값이 변경되기 직전에 실행됩니다.
useEffect(() => {
const [state, serstate] = useState(initialState);
return() => {
// return하는 함수를 clean up합니다.
}
}, [state,props.a]) // 의존성 배열
useEffect를 통해 간략해지는 코드를 보자!
useEffect을 사용 안하고 클래스형 컴포넌트를 사용한 경우
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
tick() {
this.setState({
date: new Date()
});
}
componentDidMount() {
console.log("componentDidMount");
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentDidUpdate(){
console.log("componentDidUpdate");
console.log(this.state.date);
}
componentWillUnmount(){
console.log("componentWillUnmount");
console.log(this.timerID);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
함수형 컴포넌트인 uiseEffect사용한 경우
import React, { useState, useEffect } from "react";
function Clock() {
const [date, setDate] = useState(new Date());
function tick() {
setDate(new Date());
}
// componentDidMount + componentDidUpdate
useEffect(() => {
console.log("componentDidMount");
const timerId = setInterval(tick, 1000);
// 클린업 함수 (componentWillUnmount와 동일)
return () => clearInterval(timerId);
}, []);
useEffect(() => {
console.log("componentDidUpdate");
console.log(date);
}, [date]);
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
export default Clock;
'리액트' 카테고리의 다른 글
[React] SPA와 react-router-dom (0) | 2025.04.10 |
---|---|
[React] - 리스트와 key (0) | 2025.04.09 |
[React] Lifecycle 자세히 알아보기 (0) | 2025.04.04 |
[React] State 자세히 알아보기 (0) | 2025.04.03 |
[React] CRA 없이 리액트 사용하기 (0) | 2025.04.01 |