> For the complete documentation index, see [llms.txt](https://docs.hackle.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hackle.io/development-guide/react.md).

# React

{% hint style="info" %}
Hackle React SDK는 React 16.8 이상 버전을 지원합니다.

React SDK는 [JavaScript SDK](/development-guide/javascript.md) 를 기반으로 동작합니다.
{% endhint %}

## 의존성 추가

[![](https://img.shields.io/npm/v/%40hackler%2Freact-sdk)](https://www.npmjs.com/package/@hackler/react-sdk)

{% tabs %}
{% tab title="NPM" %}

```shell
npm install --save @hackler/react-sdk
```

{% endtab %}

{% tab title="YARN" %}

```shell
yarn add @hackler/react-sdk
```

{% endtab %}
{% endtabs %}

## SDK 초기화

SDK를 사용하기 위해서 반드시 HackleReactSDKClient 를 초기화 해야 합니다.

* `HackleReactSDKClient`는 SDK의 기능을 사용하기 위한 메소드들을 제공하는 클래스입니다.
* SDK 키는 핵클 서비스의 대시보드 안에 위치한 [SDK 연동 정보](https://dashboard.hackle.io/config/sdk-setting) 에서 확인하실 수 있습니다.

어플리케이션 초기화 단계에 핵클 서버와 데이터 동기화를 위한 통신을 진행합니다. 일반적으로 이 시간은 수 밀리 초에 불과합니다. 동기화가 완료되면 즉시 렌더링이 진행됩니다.

{% hint style="warning" %}
**초기화가 완료되기 전에는 SDK 기능을 호출하지 마세요.**

초기화는 비동기로 진행되며, 핵클 서버와의 동기화가 끝나야 완료됩니다. 초기화가 완료되기 전에 SDK 기능을 호출하면 SDK가 정상적으로 동작하지 않거나 이벤트가 유실될 수 있습니다.

* **A/B 테스트, 기능 플래그, 리모트 컨피그가 정상 동작하지 않습니다.** 실제 분배 결과 대신 기본 그룹(`A`), 꺼짐(`false`), 호출 시 전달한 기본값을 리턴합니다. (사유: `SDK_NOT_READY`)
* **노출 이벤트가 기록되지 않습니다.** 사용자가 실제로 실험 대상이었더라도 노출로 집계되지 않아 실험 결과가 왜곡될 수 있습니다.
* **이벤트가 유실될 수 있습니다.** `track()`으로 수집한 이벤트가 전송되지 않을 수 있습니다.
* **이벤트에 세션 ID가 부정확하게 남을 수 있습니다.**
* **인앱 메시지가 노출되지 않습니다.** 발동 조건은 이벤트가 수집되는 시점에 평가되며, 초기화 완료 전에 수집된 이벤트는 초기화 이후 다시 평가되지 않습니다.

SDK 기능 호출은 반드시 초기화 완료 이후에 실행해 주세요.
{% endhint %}

{% hint style="warning" %}
Google Tag Manager (GTM) 사용시 주의 사항

GTM을 사용하여 연동을 진행할 경우, Hackle SDK 초기화를 하고, SDK를 GTM 에서 접근할 수 있도록 window에 추가 선언이 필요합니다.
{% endhint %}

{% tabs %}
{% tab title="React" %}

```javascript
import { createInstance, HackleProvider } from "@hackler/react-sdk";

// YOUR_BROWSER_SDK_KEY 자리에 SDK 키를 넣습니다.
const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY")

ReactDOM.render(
  <HackleProvider hackleClient={hackleClient}>
    <YourApp />
  </HackleProvider>,
  document.getElementById('root')
);

// GTM 연동 시 추가 script
window.hackleClient = hackleClient
```

{% endtab %}

{% tab title="Next.js" %}

```javascript
import {createInstance, HackleProvider} from "@hackler/react-sdk";

// YOUR_BROWSER_SDK_KEY 자리에 SDK 키를 넣습니다.
const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY")

function MyApp({Component, pageProps}) {
  return (
    <HackleProvider hackleClient={hackleClient} supportSSR>
      <Component {...pageProps} />
    </HackleProvider>
  )
}

export default MyApp
```

{% endtab %}

{% tab title="Gatsby" %}

```javascript
import {createInstance, HackleProvider} from "@hackler/react-sdk";

// YOUR_BROWSER_SDK_KEY 자리에 SDK 키를 넣습니다.
const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY")

function App() {
  return (
    <HackleProvider hackleClient={hackleClient} supportSSR>
      <YourApp />
    </HackleProvider>
  )
}

export default App
```

{% endtab %}
{% endtabs %}

### 초기화 설정정보

설정정보를 포함하여 SDK를 초기화 할 수 있습니다.

{% tabs %}
{% tab title="React" %}

```javascript
import { createInstance, HackleProvider } from "@hackler/react-sdk";

// 설정정보를 포함하여 초기화
const config = {
  debug: true
};

const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY", config);

ReactDOM.render(
  <HackleProvider hackleClient={hackleClient}>
    <YourApp />
  </HackleProvider>,
  document.getElementById('root')
);
```

{% endtab %}

{% tab title="Next.js" %}

```javascript
import {createInstance, HackleProvider} from "@hackler/react-sdk";

// 설정정보를 포함하여 초기화
const config = {
  debug: true
};

const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY", config);

function MyApp({Component, pageProps}) {
  return (
    <HackleProvider hackleClient={hackleClient} supportSSR>
      <Component {...pageProps} />
    </HackleProvider>
  )
}

export default MyApp
```

{% endtab %}
{% endtabs %}

#### 모든 설정옵션

<table data-full-width="false"><thead><tr><th width="213.57">설정</th><th width="295.49">기능</th><th width="125.81">기본값</th><th width="108.1">지원 버전</th></tr></thead><tbody><tr><td><code>debug</code></td><td>모든 기능에 대한 로그를 콘솔에 출력합니다.</td><td><code>false</code></td><td>1.0.0+</td></tr><tr><td><code>pollingIntervalMillis</code></td><td>대시보드에서 설정한 정보를 주기적으로 업데이트 할 수 있습니다.<br>최솟값 : 60000 (60초)</td><td><code>-1</code></td><td>11.1.0+</td></tr><tr><td><code>exposureEventDedupIntervalMillis</code></td><td>동일한 사용자가 연속으로 발생시킨 동일한 A/B 테스트, 기능플래그 분배결과에 대한 노출 이벤트를 제거합니다.<br>최솟값: 1000 (1초)<br>최댓값: 3600000 (1시간)</td><td><p><code>60000</code>(1분 / 11.23.0 버전 이상)</p><p><code>-1</code>(중복제거 하지 않음 / 11.23.0 버전 미만)</p></td><td>11.1.0+</td></tr><tr><td><code>sessionTimeoutMillis</code> (deprecated)</td><td>세션만료 시간을 설정합니다. <code>sessionPolicy</code>를 사용해 주세요.</td><td><code>1800000</code> (30분)</td><td>11.8.0+</td></tr><tr><td><code>devTool</code></td><td><a href="/development-guide/react/react-user-explorer.md">사용자 탐색</a>을 사용할 수 있도록 합니다.</td><td><code>undefined</code></td><td>11.13.0+</td></tr><tr><td><code>autoOpenDevTool</code></td><td>사용자 탐색 버튼이 자동으로 나타나도록 하는 옵션입니다.</td><td><code>false</code></td><td>11.13.0+</td></tr><tr><td><code>user</code></td><td>초기화 시점에 사용자를 주입합니다.</td><td><code>undefined</code></td><td>11.22.3+</td></tr><tr><td><code>sessionPolicy</code></td><td>세션 유지 조건과 만료 조건을 설정합니다.</td><td><p><code>ALWAYS_NEW_SESSION</code> ,</p><p><code>1800000</code></p></td><td>11.54.0+</td></tr><tr><td><code>optOutTracking</code></td><td>옵트아웃 활성화 여부.</td><td><code>false</code></td><td>11.54.0+</td></tr><tr><td><code>evaluationMode</code></td><td>평가 방식을 설정합니다.</td><td><code>local</code></td><td>12.0.0+</td></tr></tbody></table>

#### 평가 방식 설정

평가를 SDK에서 직접 수행할지, 핵클 서버가 미리 수행한 결과를 조회할지 선택할 수 있습니다.\
설정하지 않으면 기본값인 `"local"`(로컬 평가)로 동작합니다.

```javascript
import { createInstance, HackleProvider } from "@hackler/react-sdk";

const config = {
    evaluationMode: "remote"
};

const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY", config);

ReactDOM.render(
  <HackleProvider hackleClient={hackleClient}>
    <YourApp />
  </HackleProvider>,
  document.getElementById('root')
);
```

{% hint style="warning" %}
원격 평가를 사용하면 브라우저에 사용자 정보를 저장하지 않습니다. 기존에 로컬 평가를 사용하며 저장된 사용자 정보가 있는 경우 삭제 처리합니다.

두 방식의 차이와 선택 기준은 [평가 방식](/development-guide/sdk/evaluation-mode.md) 문서를 참고 바랍니다.
{% endhint %}

#### 세션 정책 설정

세션 정책을 설정하여 세션의 유지 조건과 만료 조건을 제어할 수 있습니다.

```javascript
import { createInstance, HackleProvider, HackleSessionPersistConditions } from "@hackler/react-sdk";

const config = {
    sessionPolicy: {
        timeoutMillis: 3600000,
        persistCondition: HackleSessionPersistConditions.NULL_TO_USER_ID
    }
};

const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY", config);

ReactDOM.render(
  <HackleProvider hackleClient={hackleClient}>
    <YourApp />
  </HackleProvider>,
  document.getElementById('root')
);
```

#### 초기화 시 사용자 주입

config에 user를 설정한 경우 유저 정보를 포함하여 SDK를 초기화 할 수 있습니다.

* 유저 정보를 포함하지 않으면 쿠키에 저장된 유저 정보를 사용합니다.
* 유저 정보를 포함하는 경우 쿠키에 저장된 유저 정보는 사용하지 않습니다.
* 쿠키에 저장된 유저 정보가 없는 경우 Hackle Device ID를 device id로 가지고 유저를 사용합니다.

{% hint style="info" %}
유저 정보는 SDK 초기화 이후에도 유저 정보 설정 함수를 통해 자유롭게 수정 할 수 있습니다.
{% endhint %}

{% hint style="warning" %}
초기화 시 주입한 유저 정보와 쿠키에 저장된 유저 정보는 병합하지 않습니다.

ex) 쿠키에 `userId: A` 가 저장된 상태에서 초기화 시 `deviceId: B` 를 주입하는 경우, `userId: null, deviceId: B`인 유저로 설정됩니다.
{% endhint %}

{% hint style="warning" %}
React SDK 12.0.0 부터 `HackleProvider`의 `user` prop은 값이 변경된 경우에만 적용되며, 적용 시 기존 사용자 정보를 병합하지 않고 대체합니다.

`user` prop 방식과 사용자 정보 변경 함수(`setUser`, `setUserId`, `setDeviceId` 등) 방식을 함께 사용하면 사용자 정보가 유실될 수 있습니다. 두 방식 중 하나만 사용해주세요. 초기 사용자 정보만 필요한 경우 `user` prop 대신 config의 `user` 사용을 권장합니다.
{% endhint %}

{% tabs %}
{% tab title="React" %}

```javascript
import { createInstance, HackleProvider } from "@hackler/react-sdk";

const user = {
  userId: "LOGIN_ID",
  deviceId: "CUSTOM_DEVICE_ID"
};

const config = {
  debug: true,
  user: user
};

const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY", config);

ReactDOM.render(
  <HackleProvider hackleClient={hackleClient}>
    <YourApp />
  </HackleProvider>,
  document.getElementById('root')
);
```

{% endtab %}

{% tab title="Next.js" %}

```javascript
import {createInstance, HackleProvider} from "@hackler/react-sdk";

const user = {
  userId: "LOGIN_ID",
  deviceId: "CUSTOM_DEVICE_ID"
};

const config = {
  debug: true,
  user: user
};

const hackleClient = createInstance("YOUR_BROWSER_SDK_KEY", config);

function MyApp({Component, pageProps}) {
  return (
    <HackleProvider hackleClient={hackleClient} supportSSR>
      <Component {...pageProps} />
    </HackleProvider>
  )
}

export default MyApp
```

{% endtab %}
{% endtabs %}

### 대시보드 설정 정보 갱신

대시보드 설정 정보를 명시적으로 갱신 할 수 있습니다.

{% hint style="warning" %}
해당 함수는 60초에 한번 제한적으로 호출할 수 있습니다.
{% endhint %}

```javascript
await hackleClient.fetch();
```

React SDK 12.0.0 부터 `fetch()` 완료 후 훅(`useVariation` 등)이 최신 설정 정보 기준으로 다시 평가됩니다.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.hackle.io/development-guide/react.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
