react-useEffect

ttomy·2022년 3월 12일
0

useEffect

컴포넌트가 렌더링될 때,state가 변화할 때 마다 특정 함수가 시행되게 할 수 있다.

  • 기본형태
    useEffect(함수,deps)
  • 함수: 조건이 만족되었을 때 수행할 작업
  • deps: 검사하고자 하는 특정값,배열
    [name]이 들어간다면 name값이 바뀔 때마다 인자의 함수가 시행됨
    빈 배열이 들어간다면 최초 렌더링 시에만 함수가 시행됨

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();
 }, []);

0개의 댓글