> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-v6-beta2-flutter-uikit.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Overview

> Get started with CometChat React Native SDK - initialize, authenticate users, and integrate chat functionality into your React Native application.

<Info>
  **Quick Reference** - Copy-paste ready initialization and login:

  ```javascript theme={null}
  useEffect(() => {
    const initCometChat = async () => {
      const appSetting = new CometChat.AppSettingsBuilder()
        .subscribePresenceForAllUsers()
        .setRegion("REGION")
        .autoEstablishSocketConnection(true)
        .build();
      await CometChat.init("APP_ID", appSetting);
      
      // Login user (check if already logged in first)
      const loggedInUser = await CometChat.getLoggedinUser();
      if (!loggedInUser) {
        await CometChat.login("USER_UID", "AUTH_KEY");
      }
    };
    initCometChat();
  }, []);
  ```
</Info>

This guide demonstrates how to add chat to a React Native application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/react-native/key-concepts) guide.

#### I want to integrate with my app

1. [Get your Application Keys](#get-your-application-keys)
2. [Add the CometChat Dependency](#add-the-cometchat-dependency)
3. [Initialize CometChat](#initialize-cometchat)
4. [Register and Login your user](#register-and-login-your-user)
5. [Integrate our UI Kits](#integrate-our-ui-kits)

#### I want to explore a sample app (includes UI)

Open the app folder in your favorite code editor and follow the steps mentioned in the `README.md` file.

<Card title="React Native Sample App" icon="github" href="https://github.com/cometchat/cometchat-uikit-react-native">
  Explore a complete React Native chat application with UI components
</Card>

## Get your Application Keys

[Signup for CometChat](https://app.cometchat.com) and then:

<Steps>
  <Step title="Create a new app">
    Create a new application in your CometChat dashboard
  </Step>

  <Step title="Get your credentials">
    Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region**
  </Step>
</Steps>

## Add the CometChat Dependency

Install the package as an NPM module:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @cometchat/chat-sdk-react-native
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @cometchat/chat-sdk-react-native
    ```
  </Tab>
</Tabs>

**To integrate the CometChat React Native SDK, you need to install one more dependency.**

### Async-Storage

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @react-native-async-storage/async-storage
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @react-native-async-storage/async-storage
    ```
  </Tab>
</Tabs>

<Note>
  v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please install the Calling dependency (`@cometchat/calls-sdk-react-native`).

  ```bash theme={null}
  npm install @cometchat/calls-sdk-react-native
  ```

  The calling component requires some configuration. Please follow the steps mentioned in the [Calling Component Configuration](#calling-component-configuration) section below.
</Note>

## Calling Component Configuration

For `@cometchat/calls-sdk-react-native`, please make sure you add the following additional dependencies & permissions.

### Required Dependencies

```json theme={null}
{
  "@cometchat/chat-sdk-react-native": "^4.0.18",
  "@react-native-async-storage/async-storage": "^2.2.0",
  "@react-native-community/netinfo": "^11.4.1",
  "react-native-background-timer": "^2.4.1",
  "react-native-callstats": "^3.73.22",
  "react-native-webrtc": "^124.0.6"
}
```

### Permissions

<Tabs>
  <Tab title="Android">
    Add the following permissions to your `AndroidManifest.xml`:

    ```xml theme={null}
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    ```
  </Tab>

  <Tab title="iOS">
    Add the following keys to your `Info.plist`:

    ```xml theme={null}
    <key>NSCameraUsageDescription</key>
    <string>This is for Camera permission</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>This is for Mic permission</string>
    ```
  </Tab>
</Tabs>

### Platform-Specific Configuration

<AccordionGroup>
  <Accordion title="Android Configuration">
    Go to the `./android` folder and open the project level `build.gradle` file. Add all repository URLs in the repositories block under the `allprojects` section. Also in the same file in the `buildscript` section in the `ext` block, make sure you have set **minSdkVersion** to **24**.

    **Add Repository URL:**

    ```gradle theme={null}
    allprojects {
      repositories {
        maven {
          url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/"
        }
      }
    }
    ```

    **Set Minimum SDK Version:**

    ```gradle theme={null}
    buildscript {
      ext {
        buildToolsVersion = "29.0.2"
        minSdkVersion = 24
        compileSdkVersion = 29
        targetSdkVersion = 29
      }
    }
    ```
  </Accordion>

  <Accordion title="iOS Configuration">
    Please update the minimum target version in the Podfile. Go to the `./ios` folder and open the Podfile. In the Podfile, update the platform version to `11.0`:

    ```ruby theme={null}
    platform :ios, '11.0'
    ```

    Open the `ios/App` folder and run `pod install`. This will create an `App.xcworkspace` file. Open this and run the app.
  </Accordion>
</AccordionGroup>

## Initialize CometChat

The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters:

| Parameter     | Description                                                                       |
| ------------- | --------------------------------------------------------------------------------- |
| `appID`       | Your CometChat App ID                                                             |
| `appSettings` | An object of the `AppSettings` class created using the `AppSettingsBuilder` class |

The `AppSettings` class allows you to configure the following settings:

| Setting                                    | Description                                                                                                                                                                                                                                          |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Region**                                 | The region where your app was created (mandatory)                                                                                                                                                                                                    |
| **Presence Subscription**                  | Represents the subscription type for user presence (real-time online/offline status). See [Presence Subscription](/sdk/react-native/user-presence)                                                                                                   |
| **autoEstablishSocketConnection(boolean)** | When set to `true`, the SDK manages the web-socket connection internally. When set to `false`, you manage the connection manually. Default: `true`. See [Managing connections manually](/sdk/react-native/managing-web-sockets-connections-manually) |
| **overrideAdminHost(adminHost: string)**   | Uses a custom admin URL instead of the default. Used for dedicated CometChat deployments                                                                                                                                                             |
| **overrideClientHost(clientHost: string)** | Uses a custom client URL instead of the default. Used for dedicated CometChat deployments                                                                                                                                                            |

You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `App.tsx` file.

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    let appID = "APP_ID";
    let region = "REGION";

    // Build app settings with presence subscription and auto socket connection
    let appSetting = new CometChat.AppSettingsBuilder()
      .subscribePresenceForAllUsers()
      .setRegion(region)
      .autoEstablishSocketConnection(true)
      .build();

    // Initialize CometChat
    CometChat.init(appID, appSetting).then(
      () => {
        console.log("Initialization completed successfully");
      },
      (error) => {
        console.log("Initialization failed with error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    let appID: string = "APP_ID",
      region: string = "APP_REGION",

    // Build app settings with presence subscription and auto socket connection
    let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder()
      .subscribePresenceForAllUsers()
      .setRegion(region)
      .autoEstablishSocketConnection(true)
      .build();

    // Initialize CometChat
    CometChat.init(appID, appSetting).then(
      (initialized: boolean) => {
        console.log("Initialization completed successfully", initialized);
      },
      (error: CometChat.CometChatException) => {
        console.log("Initialization failed with error:", error);
      }
    );
    ```
  </Tab>
</Tabs>

<Warning>
  Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` with your **App Region** in the above code.
</Warning>

## Register and Login your user

Once initialization is successful, you will need to create a user. To create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful.

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    let authKey = "AUTH_KEY";
    let uid = "user1";
    let name = "Kevin";

    // Create a new user object
    let user = new CometChat.User(uid);
    user.setName(name);

    // Register the user with CometChat
    CometChat.createUser(user, authKey).then(
      (user) => {
        console.log("user created", user);
      },
      (error) => {
        console.log("error", error);
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    let authKey: string = "AUTH_KEY",
      UID: string = "user1",
      name: string = "Kevin";

    // Create a new user object
    var user = new CometChat.User(UID);
    user.setName(name);

    // Register the user with CometChat
    CometChat.createUser(user, authKey).then(
      (user: CometChat.User) => {
        console.log("user created", user);
      },
      (error: CometChat.CometChatException) => {
        console.log("error", error);
      }
    );
    ```
  </Tab>
</Tabs>

<Note>
  Make sure that `UID` and `name` are specified as these are mandatory fields to create a user.
</Note>

Once you have created the user successfully, you will need to log the user into CometChat using the `login()` method.

We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once.

<Warning>
  **Security Warning:** This straightforward authentication method using Auth Key is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [Auth Token](/sdk/react-native/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security.
</Warning>

<Tabs>
  <Tab title="JavaScript">
    ```javascript theme={null}
    let UID = "cometchat-uid-1";
    let authKey = "AUTH_KEY";

    // Check if user is already logged in
    CometChat.getLoggedinUser().then(
      (user) => {
        if (!user) {
          // Login the user if not already logged in
          CometChat.login(UID, authKey).then(
            (user) => {
              console.log("Login Successful:", { user });
            },
            (error) => {
              console.log("Login failed with exception:", { error });
            }
          );
        }
      },
      (error) => {
        console.log("Some Error Occured", { error });
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    var UID: string = "cometchat-uid-1",
      authKey: string = "AUTH_KEY";

    // Check if user is already logged in
    CometChat.getLoggedinUser().then(
      (user: CometChat.User) => {
        if (!user) {
          // Login the user if not already logged in
          CometChat.login(UID, authKey).then(
            (user: CometChat.User) => {
              console.log("Login Successful:", { user });
            },
            (error: CometChat.CometChatException) => {
              console.log("Login failed with exception:", { error });
            }
          );
        }
      },
      (error: CometChat.CometChatException) => {
        console.log("Some Error Occured", { error });
      }
    );
    ```
  </Tab>
</Tabs>

<Warning>
  Make sure you replace the `AUTH_KEY` with your CometChat **Auth Key** in the above code.
</Warning>

<Info>
  **Test Users Available:** We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`.
</Info>

The `login()` method returns the `User` object containing all the information of the logged-in user.

<Warning>
  **UID Format:** UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed.
</Warning>

## Integrate our UI Kits

Please refer to the [React Native UI Kit](/ui-kit/react-native/overview) section to integrate React Native UI Kit inside your app.

<AccordionGroup>
  <Accordion title="Best Practices">
    * Always call `init()` before any other CometChat method
    * Call `init()` on app startup (preferably in `App.tsx`)
    * Use `getLoggedinUser()` to check login state before calling `login()`
    * Store user credentials securely and never expose Auth Keys in client-side code for production
    * Use Auth Token instead of Auth Key for production environments
  </Accordion>

  <Accordion title="Troubleshooting">
    * **Initialization fails:** Verify your App ID and Region are correct
    * **Login fails:** Ensure the user exists or create them first using `createUser()`
    * **Network errors:** Check internet connectivity and firewall settings
    * **Calling not working:** Verify all calling dependencies are installed and permissions are granted
    * **iOS build fails:** Run `pod install` in the `ios` directory after adding dependencies
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Key Concepts" icon="book" href="/sdk/react-native/key-concepts">
    Understand the fundamental concepts of CometChat
  </Card>

  <Card title="Authentication" icon="lock" href="/sdk/react-native/authentication-overview">
    Learn about secure authentication methods including Auth Tokens
  </Card>

  <Card title="Send Messages" icon="paper-plane" href="/sdk/react-native/messaging">
    Start sending text, media, and custom messages
  </Card>

  <Card title="UI Kit Integration" icon="palette" href="/ui-kit/react-native/overview">
    Add pre-built UI components to your app
  </Card>
</CardGroup>
