엄코딩의 개발 일지

React Native Hook을 사용하게 된 가장 큰 이유는 Hook을 학습하게 된 가장 큰 이유는 Class를 쓰지 않고 function에서 state를 관리할 수 있기 때문이다. 이렇게 된다면 함수형 컴포넌트를 사용하면서, '독립적으로 state를 관리할 수 있게 되고, 테스트가 편해질 것' 이라고 생각했다. 

 

1.  함수형 컴포넌트 상태 관리 ( useState )

 

Hook을 사용하기 전에는 클래스단에서 state를 선언하고 가감연산 부분에서 setState를 해주었을 것이다. 하지만 Hook을 사용하게 된다면 이제는 함수형 컴포넌트에서도 state를 쉽게 관리할 수 있다.

Counter(): JSX.Element {

    const [count, setCount] = useState(0);
    
    const onCountUp = () => {
      setCount(count + 1);
    };
    
    const onCountDown = () => {
      setCount(count - 1);
    };
    
    return (
      <View style={styles.container}>
        <View style={styles.touchArea}>
          <TouchableOpacity style={styles.upContainer} onPress={onCountUp}>
            <CustomText style={styles.title}>UP</CustomText>
          </TouchableOpacity>
          <TouchableOpacity style={styles.downContainer} onPress={onCountDown}>
            <CustomText style={styles.title}>DOWN</CustomText>
          </TouchableOpacity>
        </View>

        <View style={styles.countContainer}>
          <CustomText style={styles.title}>{count}</CustomText>
        </View>
      </View>
    );
  }

 

위 코드는 Hook을 설명할 때 많이 사용되는 가감연산만을 구현하고 있다. useState는 현재 state값과 state를 업데이트 할 수 있는 함수를 반환하고 초기값을 받는다. 즉, 클래스로 작성했을때에는 아래 코드 느낌이었을 것이다.

this.state = { count : 0 }
 setCount(value : number){
    this.setState(
      count : value
    )
  }

하지만 위 절차를 줄여주고, 함수내에서 state를 쉽게 관리할 수 있다는 점이 Hook의 장점이다.

 

2. 함수형 컴포넌트 라이프 사이클 ( useEffect )

useEffect는 컴포넌트가 렌더링 될 때마다 특정 작업을 실행할 수 있도록하는 Hook이다. 

 

 useEffect(() => {
      showLog('렌더링');
      showLog('count : ' + count);
    });

 

위 코드는 함수형 컴포넌트가 렌더링 될 때 실행되는 코드다. 만약 마운트 될 때만 실행하고 싶다면 useEffect 함수의 2번째 인자로 비어있는 배열을 넣어주면 된다.

 

 useEffect(() => {
      showLog('렌더링 완료.');
      showLog('count : ' + count);
    }, []);

 

위 코드는 마운트 됬을 때만 동작하게된다.

 

만약 특정 값이 변할때만 실행하고 싶은 코드가 있다면 아래 코드처럼 특정 값을 배열에 넣어주면 된다.

 useEffect(() => {
      showLog('렌더링 완료.');
      showLog('count : ' + count);
    }, [count]);

 

useEffect함수는 기본적으로 렌더링 된 후에 실행되고, 두번째 파라미터에 따라 실행 조건이 변한다.

만약 컴포넌트가 언마운트 되기 전, 업데이트 되기 직전에 특정 작업을 수행하고 싶다면 아래 코드처럼 작성하면 된다.

 

 useEffect(() => {
      showLog('렌더링 완료.');
      showLog('count : ' + count);
      return () => {
        console.log('cleanup');
      };
    });

 

결론 진작 Hook을 사용했어야 했다.

 

 

 

참고자료 : https://velog.io/@velopert/react-hooks