componentDidUpdate(prevProps, prevState){ if (prevState.count == this.state.count){ document.title = `You clicked ${this.state.count} times`; } }
class로 구현했을 때 componentDidUpdate가 실행될 때는 props 또는 state가 바뀔 때마다 실행되었습니다.
그 때의 인자로 이전의 props 값과 이전의 state값을 전달하는데 이전의 값과 이후의 값이 변경된 값을 비교해서 다를 때 작업을 처리하면 불필요한 처리를 하지 않음으로써 성능을 더욱 높일 수 있습니다.
var numberState = useState(props.initNumber); var number = numberState[0]; var setNumber = numberState[1]; useEffect(function(){ // 첫번째 인자로는 함수가 와야합니다. console.log('func => useEffect(componentDidMount & componentDidUpdate'); document.title = number; return function(){ console.log('func => useEffect return') } }, [number]); // 배열안에
위의 예제는 문서의 title 값을 바꾸는데, number 라는 state만 참고해서 어떠한 작업을 실행합니다.
그 얘기는 number의 값이 바뀌지 않았을 경우에는 따로 작업을 할 필요가 없습니다.
이럴 때에 useEffect를 이용하면 number의 값이 바뀌었을 때만 이 함수가 호출되도록 할 수 있습니다.
useEffect 마지막에 있는 배열 안의 상태값이 바뀌었을 때만, 첫번째 useEffect의 인자인 callback 함수가 호출되도록
약속되어 있습니다.
Skipping effect
component lifecycle을 모방한 useEffect를 보면 componentDidMount와 componentDidUpdate 둘 다 실행되는 것을 알수 있습니다. 그러나 어떠한 경우에는 둘 중 하나만 필요할 경우가 생깁니다.
useEffect(function(){ // 첫번째 인자로는 함수가 와야합니다. console.log('func => useEffect(componentDidMount & componentDidUpdate'); document.title = number; return function(){ console.log('func => useEffect return (componentDidMount & componentDidUpdate') } }); // 두 번째 인자가 없을 경우 똑같다
useEffect에서 위와 같이 useEffect에 두 번째 인자가 없을 경우에는 componentDidMount 와 componentDidUpdate가 똑같은 것입니다.
만약, 여기서 componentDidMount 만 하고 싶다면, 빈 배열을 전달합니다.
useEffect(function(){ // 첫번째 인자로는 함수가 와야합니다. console.log('func => useEffect(componentDidMount'); document.title = number; return function(){ console.log('func => useEffect return (componentDidMount)') } }, []); // 두번째 인자가 빈 배열일 경우 componentDidMount만 실행
빈 배열이 전달되면 1회는 실행되지만, 그 이후에는 실행이 되지 않습니다.
'Language > React' 카테고리의 다른 글
[React] 배열에 항목 추가하기 (0) | 2020.12.28 |
---|---|
[React] 배열 렌더링하기 (0) | 2020.12.28 |
[React] 클래스에서 라이프 사이클 구현하기 (0) | 2020.12.26 |
[React] 함수에서 state 사용법 - hook (0) | 2020.12.26 |
[React] props vs State (0) | 2020.12.25 |
댓글