강신규

[React] useEffect란 본문

Framework/React

[React] useEffect란

kangnew 2025. 1. 2. 09:55

useEffect란

어떠한 컴포넌트가

Mount(화면에 첫 렌더링, 시작)되었을 때

Update(재렌더링, 다시)되었을 때

Unmount(화면에서 끝날 때, 종료) 되었을 때 특정 작업을 처리해주고 싶으면 사용하면 된다

 

useEffect함수는 콜백 함수를 받습니다.


useEffect의 사용방법으로는 2가지가 존재하는데 

첫 번째 방법

useEffect(() => {
  // 실행하고 싶은 코드
});

- 렌더링이 될때마다 실행

두 번째 방법(인자)

useEffect(() => {
  // 실행하고 싶은 코드
}, [value]);

- 화면에 첫 렌더링이 될 때 실행

- value값이 바뀔 때 실행

 


Clean Up  - 정리

useEffect에 어떤 서비스를 구독하는 기능을 넣었다면, 나중에는 이 구독을 해지해주는 Clean Up(정리) 작업이 필요한데 이때 return에 콜백함수를 넣어주면은 해당 unmount 될때 return속에 있는 함수가 실행이 됩니다.

useEffect(() => {
//구독.... 
	return () => {
    	//구독해지...
    }
},[]);

 


실제사용

useEffect는 state의 값이 변경이 될 때 실행하도록 진행을 하여 type값에 따라 두 가지 흐름으로 나누었습니다.

1. state.type === "calculating"

2. state.type === "failure"

제가 원하는 작동방식은 calculating에서 유효성 검증 처리, failure에서 에러 메시지 모달 표시 을 원했습니다. state라는 하나의 타입을 관리함으로써 calculating, failure처럼 타입 관리가 편해지고 흐름에 따라 작동을 시킬 수 있었습니다.

이를 통해 여러 상태 변화 또는 비동기 작업 등을 처리해야 할 때 -> 상태 의존적인 작업을 useEffect로 관리하면은 코드가 깔끔해지고 React의 상태 관리 흐름에 맞게 작동을 할 수 있습니다.

  useEffect(() => {
    if (state.type === 'calculating') {
      if (variant === 'loan') {
        if (state.value.amount <= 0) {
          setState({
            type: 'failure',
            value: state.value,
            result: state.result,
            errorMessage: `대출금액을 입력해주시기 바랍니다.`,
            nextState: state.prevState,
            rawError: undefined,
          })
          return
        }
        if (state.value.durationInMonths <= 2) {
          setState({
            type: 'failure',
            value: state.value,
            result: state.result,
            errorMessage: `대출기간은 3개월부터 입력가능합니다.`,
            nextState: state.prevState,
            rawError: undefined,
          })
          return
        }
        if (!state.value.interestRate) {
          setState({
            type: 'failure',
            value: state.value,
            result: state.result,
            errorMessage: `금리를 입력해주시기 바랍니다.`,
            nextState: state.prevState,
            rawError: undefined,
          })
          return
        }
      }
      return
    }

    if (state.type === 'failure') {
      hide()
      const id = `${variant}-calculator-failure-alert`
      open(
        id,
        <AlertModal
          device={device}
          button={{
            label: '확인',
            onClick: () => {
              close(id)
              if (isNotNil(state.onQuitAlert)) {
                state.onQuitAlert()
              }
            },
          }}
        >
          <Text variant="body2" as="p" className="text-center break-keep">
            {state.errorMessage}
          </Text>
        </AlertModal>,
      )
      setState(state.nextState)
      return
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state])

 


결론

여러 상태 변화에 따라 의존적인 작업을 진행할때 useEffect를 사용하면 React의 상태 흐름에 맞게 작동할 수 있습니다.