728x90
아직 경험이 적어서 쓰는곳에 대해 잘은 모르지만,
open source API 가져올떄 (fetch()나 등등으로) 딱 한번만 가져오면 되니까 그럴때 사용.
1. componentDidMount
mount될때만 실행되는 코드, 두번째 인자에 빈 배열을 넣는다.
useEffect(() => {}, [])
import { useEffect, useState } from 'react';
const App = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count+1);
const decrement = () => setCount(count-1);
const notRun = '';
// count가 호출될때마다 실행된다
useEffect(()=>{
console.log(count);
})
return (
<div className="App">
<h1>Hello {count}</h1>
<button onClick={increment}>Up</button>
<button onClick={decrement}>Down</button>
</div>
);
}
export default App;
2. componentDidUpdate
mount 및 특정 변수가 변경될 때마다 실행되는 코드, 두번째 인자인 배열에 변경될 변수를 추가한다.
useEffect(() => {}, [특정 변수])
두번째 인자를 생략하면 렌더링(mount 포함) 될때마다 즉 props나 state값이 변경될 때마다 실행된다.
useEffect(() => {})
import { useEffect, useState } from 'react';
const App = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count+1);
const decrement = () => setCount(count-1);
const notRun = '';
// notRun을 호출하는곳이 없기때문에 useEffect 는 실행되지않는다.
useEffect(()=>{
console.log(count);
},notRun)
return (
<div className="App">
<h1>Hello {count}</h1>
<button onClick={increment}>Up</button>
<button onClick={decrement}>Down</button>
</div>
);
}
export default App;
3. componentWillUnmount
화면이 정리될 때(clean-up, 종료될 때) 실행되는 코드, 첫번째 함수에서 어떤 코드를 리턴하면 된다.
useEffect(() => {return (...);}, [])
728x90
'Web > React' 카테고리의 다른 글
React - Styled Components 01 (0) | 2022.05.16 |
---|---|
React Hook 03 - useRef() (0) | 2022.05.16 |
React Hook 01 - useState() (0) | 2022.05.15 |
React - 파일 만들때는 .jsx파일 (0) | 2022.05.14 |
React - Component (0) | 2022.05.13 |