# reactivity

svelte의 가장 강조되고 있는 기능 중에 하나가 바로 reactivity 즉 손쉬운 반응성 구현입니다.

반응성이란 선언된 state의 상태에 따라서 특별한 호출 없이 HTML 영역 및 바라보는 변수 들의 상태가 바로바로 변경되는 것 이라고 생각하시면 되겠습니다.

간단한 예제를 통해 이 반응성을 알아보겠습니다.

예를 들어 다음과 같은 예제를 만들었을 때 p태그 안의 내용은 특별한 직접적인 조작 없이 state의 상태에 따라서 보이고 안보이고가 결정됩니다. 이것이 바로 reactivity 즉 반응성입니다.

```
<script>
	// state 생성
	let active = false
</script>

<span><input type="checkbox" bind:checked={active} /> 상태</span>

<br>

<p class:view={!active} >active is {active}</p>

<style>
	.view {
		display: none;
	}
</style>
```

작성된 코드를 보면 좀 더 이해가 쉬울 것입니다. 다음은 count 변수를 주고, 이 변수가 +1 씩 증가하는 버튼을 만들어 count 값이 증가하는 코딩입니다.

```
<script>
let count = 0

function handleClick() {
	// 이벤트 코드
	count += 1
}

</script>

<button on:click={handleClick} >
	클릭수 { count } {count === 1 ? 'time' : 'times'}
</button>

```

handleClick액션을 주면 count 값이 계속 증가하게 됩니다. 그리고 이 증가한 내용은 즉시 html영역에 반영이 됩니다. html영역을 값에 따라 변화를 주기위해 특별한 호출이 필요하지 않습니다. 단지 변수를 선언하고, 그 변수를 바라 보게만 하면 되는 것입니다.

#### 삼항연산자 설명

```
변수 == 값 ? '참일때' : '거진일때'

위의 연산자는 아래의 if문을 심플하게 구현한 코드입니다. 이것을 삼항연산자라고 합니다. 

if(변수) {
	 '참'
}
else {
	'거짓'
}
```

$: 설명

HTML영역 뿐만 아니라 스크립트 영역도 이와 비슷한 방식으로 작성이 가능합니다. let, const로 변수를 지정하지 않고 반응성을 주고 싶은 변수는 `$:`로 정의하기만 하면 됩니다.

예제로 조금전 만든 코드에 doubled라는 변수를 $:로 선언해 어떻게 작동하는지 보도록 하겠습니다.

```
<script>
let count = 0
$: doubled = count * 2

*$*: {
	console.log( count )
	console.log( doubled )
}

function handleClick() {
	// 이벤트 코드
	count += 1
}

</script>

<button on:click={handleClick}>
	클릭수 { count } {count === 1 ? 'time' : 'times'}
</button>

<p>{count} 두배는 {doubled} <p/>

```

count가 변화가 일어나면 자동으로 doubled도 값이 변하고 다시 이를 바라보는 영역에 적용되는 것을 볼 수 있습니다.

```
<script>
let count = 0
$: doubled = count * 2

$: if(count >= 10) {
	alert('카운트가 10을 넘었습니다. ')
	count = 9
}

$: {
	console.log( count )
	console.log( doubled )
}

function handleClick() {
	// 이벤트 코드
	count += 1
}

</script>

<button on:click={handleClick}>
	클릭수 { count } {count === 1 ? 'time' : 'times'}
</button>

<p>{count} 두배는 {doubled} <p/>

```

주의할 점은 선언된 값을 변화할 때 push, slice 등 으로 변수를 직접 변화를 주기만 해서는 적용이 안됩니다.

꼭 `변수 = 변수.push` 이런 식으로 재할당 해주셔야 합니다.

물론 svelte가 아닌 react나 vue등에서도 이런 기능을 구현할 수 있지만, 선언방식이 훨씩 복잡한 것을 다음 코드 비교를 통해서 볼 수 있습니다. svelte는 그냥 $:를 선언하는 것 만으로 반응성이 깃든 기능을 만들 수 있는 것입니다.

```
-- vue

<template>
  <div>
    <button @click="handleClick">
      Clicked {{count}} {{count === 1 ? 'time' : 'times'}}
    </button>

    <p>{{count}} doubled is {{doubled}}</p>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        count: 0
      }
    },
    computed: {
      double () {
        return this.count * 2
      }
    },
		watch: {
      count (count) {
        if (count >= 10) {
          alert(`count is dangerously high!`);
          this.count = 9;
        }
      }
    },
    methods: {
      handleClick () {
        this.count += 1;
      }
    },
  }
</script>

```

[\[만들면서 배우는 Svelte\]](https://www.inflearn.com/course/%EB%A7%8C%EB%93%A4%EB%A9%B4%EC%84%9C-%EB%B0%B0%EC%9A%B0%EB%8A%94-%EC%8A%A4%EB%B2%A8%ED%8A%B8)

<div align="left"><img src="/files/-MGqwZuQK1aEaE5Bp21i" alt="만들면서 배우는 svelte"></div>


---

# 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://freeseamew.gitbook.io/svelte/3./reactivity.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.
