컴포넌트가 렌더링될 때,state가 변화할 때 마다 특정 함수가 시행되게 할 수 있다.
ex)
useEffect(()=>{
console.log('업데이트되면 실행');
},[name]);
ex)
const [articles, setArticles] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchArticles = async () => {
try {
// 요청이 시작 할 때에는 error 와 articles 를 초기화하고
setError(null);
setArticles(null);
// loading 상태를 true 로 바꿉니다.
setLoading(true);
const response = await axios.get(
'https://localhost:8080/api/articles'
);
setArticles(response.data);
// 데이터는 response.data 안에 들어있습니다.
} catch (e) {
setError(e);
}
setLoading(false);
};
useEffect(() => {
fetchArticles();
}, []);