본문 바로가기
Language/React

[React] 라이플 사이클 구현 하기 - skipping effect

by 며루치꽃 2020. 12. 27.
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회는 실행되지만, 그 이후에는 실행이 되지 않습니다. 

댓글