# useEffect

## useEffect를 이용한 데이터 변경 관리

애플리케이션을 구현하다 보면 **특정 데이터의 변경에 따라 연쇄적인 처리**를 해야 하는 경우가 발생한다. 예를 들어 국어, 영어, 수학 점수를 이용하여 총점과 평균을 계산해야 하는 프로그램이 있을 경우 각각의 점수가 변경되면 총점과 평균이 다시 계산되어야 한다. 이를 렌더링 시 계산해서 출력하도록 해도 되지만 자동 계산되도록 처리하면 좀 더 효율적이고 실시간에 가까운 데이터 관리가 가능하다.

<div align="left"><figure><img src="/files/zGjK5bGv1fhX5HfJE0b7" alt=""><figcaption></figcaption></figure></div>

## useEffect 구문

useEffect는 다음과 같은 구문 형식을 가진다.

### 모듈을 사용하지 않는 경우

```jsx
React.useEffect(함수, [감지항목]);
```

모듈을 사용하지 않고 CDN 등으로 불러오는 경우 import가 불가능하므로 React 클래스를 통해 useEffect 함수를 호출한다.

### 모듈 기반으로 개발중인 경우

```jsx
import {useEffect} from 'react';

useEffect(함수, [감지항목]);
```

npm, webpack 기반 모듈 개발 중이라면 <mark style="color:red;">import</mark>를 통해 속성 추출을 하여 사용할 수 있다.

## 예제 - 총점 및 평균 계산기

```jsx
function MainComponent(){
    const [korean, setKorean] = React.useState(0);
    const [english, setEnglish] = React.useState(0);
    const [math, setMath] = React.useState(0);
    const [total, setTotal] = React.useState(0);
    const [average, setAverage] = React.useState(0);

    React.useEffect(()=>setTotal(korean + english + math) , [korean, english, math]);
    React.useEffect(()=>setAverage(total / 3) , [total]);

    return (
        <>
            국어점수 : <input type="number" onInput={e=>setKorean(parseFloat(e.target.value))}/><br/>
            영어점수 : <input type="number" onInput={e=>setEnglish(parseFloat(e.target.value))}/><br/>
            수학점수 : <input type="number" onInput={e=>setMath(parseFloat(e.target.value))}/><br/>
            <hr/>
            총점 {total} 점 , 평균 {average} 점
        </>
    );
}

const app = ReactDOM.createRoot(document.querySelector("#app"));
app.render(<MainComponent/>);
```

{% embed url="<https://codepen.io/hiphop5782/pen/BaVdvQv>" %}

<mark style="color:blue;">`useEffect 함수`</mark>만 살펴보면 다음과 같다.

```jsx
React.useEffect(()=>setTotal(korean + english+ math), [korean,english,math]);
React.useEffect(()=>setAverage(total / 3), [total]);
```

첫 번째 useEffect에서는 **korean**, **english**, **math**에 대한 변경을 감지하여 합계를 설정하도록 구현되어 있다. 두 번째 useEffect에서는 **total**에 대한 변경을 감지하여 평균을 설정하도록 구현되어 있다. 따라서 **korean**, **english**, **math** 항목이 변경되면 연쇄적인 계산이 일어나 결과가 정상적으로 출력되는 것을 확인할 수 있다.

## 결론

useEffect는 입력 항목에 대한 정규표현식 검사, 결제 예상 금액 계산 등 다양한 항목에 적용할 수 있다.

{% hint style="info" %}
VueJS의 watch와 유사하다.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sysout.co.kr/web/develop-page/js/reactjs/cdn/component/functional-component/useeffect.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
