# 컴포넌트 통신방법 3 : context API

### context를 이용한 전달

prop를 다른 하위 컴포넌트로 값을 전달 가능하지만, 이 방법이 효율적이지 않을 때가 있습니다.

대표적인 예가 구성요소의 컴포넌트가 바로 하위가 아닌 좀 더 깊은 구조의 컴포넌트에 값을 전달할 경우인 때입니다. 이럴때 사용가능한 기능이 바로 context API입니다.

* 구성 트리리 이미지 참조

svelte에서는 getContext로 값을 담고, setCntext로 값을 받아 올 수 잇습니다. 이 기능이 좋은 점은 값을 전달하기 위해 계속해서 컴포넌트로 prop를 전달할 필요가 없다는 것입니다.

* &#x20;setContext - 전달

```
<script>
import {setContext} from 'svelte'

const setValues = {
	a: 1,
	b: 2
}

setContext('setKey', setValue)

...
```

* getContext - 받기

```
<script>
import { getContext } from 'svelte'

const getValue = getContext('setKey')

</script>

a: { getValue.a }
b: { getValue.b } 
```

#### 예제 context API

* app.svelte

```
<script>
import { setContext } from 'svelte'

import PanelComponent from './components/panelComponent.svelte'

let count = 10

function incrementCount(event) {
	count ++
}

setContext('incrementCount', incrementCount)
setContext('count', count)

</script>

<PanelComponent {count} />
```

* panelComponent.svelte

```
<script>
import ButtonComponent from './buttonComponent.svelte'

export let count
</script>

<div class="penal">
  <h1>{count}</h1>
  
  <ButtonComponent {count}  />
  
</div>

<style>
  .penal {
    padding: 20px;
    display:flex;
    flex-direction: column;
    justify-items: center;
    justify-content: space-around;
    align-items: center;
    height: 500px;
    width:400px;
    background: #e2e2e2;
    border: 1px solid #777777;
  }
</style>
```

* buttonComponent.svelte

```
<script>
import { getContext } from 'svelte'
// export let count

let handleIncrementCount = getContext('incrementCount')
let count = getContext('count')
</script>

<button on:click={handleIncrementCount} >
  increment count [{count}]
</button>
```

[\[만들면서 배우는 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./3-context-api.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.
