아하
생활

생활꿀팁

붉은왜가리38
붉은왜가리38

react 함수형 컴포넌트의 실행 순서가 어떻게 되나요?

react 에서 hook에 대해서 알아보고 있는데,

샘플 예제의 실행순서가 너무나도 헷갈립니다.

아래에 샘플을 실행시켜 보면 결과는 가장 아래에 있는 콘솔로그 캡쳐화면 처럼 나옵니다.

결과를 보면,

질문1. console.log('1')과, console.log('2')가 4번이나 찍혀 있습니다.

그렇다는건 useRequest.js와 Post.js가 4번 실행이 됐다는 것인데, 어떻게 4번이 실행이 되는지 궁금합니다.

질문2. 실행순서를 보시면,

2-1 다음에 1 이 실행

2-2 다음에 1 이 실행

2-3 다음에 1 이 실행

2-4에서 끝

이렇게 되는데, 왜 이런식으로 실행 순서가 되는지도 궁금합니다.

질문3. 마지막 실행이 왜 1-3 이 아니고 2-4 인것도 궁금합니다.

/* useReqeust.js */ import React, {useEffect, useState} from 'react'; import axios from 'axios'; const useRequest = (url) => { const [loading, setLoading] = useState(false); const [response, setResponse] = useState(null); const [error, setError] = useState(null); console.log('2'); useEffect( async () => { console.log('2-0'); setError(false); try { setLoading(true); console.log('2-1'); const res = await axios.get(url); console.log('2-2'); setResponse(res); console.log('2-3'); } catch (e) { setError(e); } setLoading(false); console.log('2-4'); }, [url] ); console.log('2-5'); return [response, loading, error]; } export default useRequest;

/* Post.js */ import React from 'react'; import useRequest from './hooks/useRequest'; const Post = () => { console.log('1'); const [response, loading, error] = useRequest('https://jsonplaceholder.typicode.com/posts/1'); console.log('1-1'); if (loading) { return <div>loading...</div>; } if (error) { return <div>Error!</div>; } if (!response) { console.log('1-2'); return null; } const {title, body} = response.data; console.log('1-3'); return ( <div> <h1>{title}</h1> <p>{body}</p> </div> ); }; export default Post;

/* App.js */ import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; // import Form from './Form'; // import Counter from './Counter'; import Post from './Post'; class App extends Component { render() { return ( <div className="App"> <Post /> </div> ); } } export default App;

1개의 답변이 있어요!