In-App Chatting in React Native
Tags: javascript, reactnative, mobile, webdev
Published: 2023-01-03 04:12:03

We often use a feature like chatting in most of the Mobile Application whether is related to banking app, Ecommerce and/or chatting apps. Its required enough time to build a chatting feature for any App in different Tech Stack, "What if i tell you a easiest way to integrate/build [In App Chatting](https://www.zegocloud.com/product/in-app-chat) feature which required almost 15 mins to build and reliable.

[**ZEGOCLOUD**](https://www.zegocloud.com/) is a library which offer may feature like Audio/Video calling, Live Streaming, Super Board, Cloud recording and much more.
In-App Chatting is one of them and I must say in my 4 years of experience I found the the platform easy to adopt in most of the features.

Here are some points which you should know before choosing any library to integrate In-App Chatting feature.

### Ultra-low latency
Have you ever miss important messages due to law latency? well in ZEGOCLOUD you don't need to worry about is as t delivers real-time messages to users with an ultra-low latency as low as 200 ms.

### Massive concurrency
One of the main issue is how to handle concurrent messages when the count is in millions, well ZEGOCLOUD handle it pretty perfectly as needs of large-scale and highly demanding live communication events

### Instruction/Steps
- Go to ZEGOCLOUD and [make a account](https://console.zegocloud.com/account/signup)
- Go to dashboard and create a APP
- Select In-app chatting feature
- Go to Service Management option from dashboard and select In-App chatting feature
![in app chatting option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cusmfd3fok68q2lcbpz.png)
- Activate it
![activation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ttci73l9n5q2iuckdher.png)
- Copy and save AppID for later use
- Run command `npm i zego-zim-react-native` to install library.
- Import SDK in Component `import ZIM from 'zego-zim-react-native';`
- Create a instance of ZIM using method create, You need **AppID **and** **appSign** which you can get from dashboard
![appSign](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s9suno416npi67moj9l0.png)
- I have define some state for later user
![component states](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qudkkprpd12avawprn9r.png)
- Create a login function that will login user to application
![login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcdhda72a957a5h0nqiz.png)
- Create sendMessage function that will help to send message to other user
![sendMessage ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kan80nk6oomn4treofua.png)
- A **useEffect** is define to handle some realtime events, If user connection state change the event **connectionStateChanged** will notify us, If any error occur the event **error** will notify us & if user get any message from other user the event **receivePeerMessage** will have that received message from where we can show it on UI
![receivePeerMessage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k71v6wr2hlkonpoekls8.png)
- We also have a **logout** & **destroy** method which will help to logout user when user leave screen and destroy the ZIM instance.
Here is my component

```
import React, { useEffect, useState } from 'react';
import { Button, TextInput, View, Text } from 'react-native';
import ZIM from 'zego-zim-react-native';
ZIM.create({ appID: ******, appSign: '***********************' })
const zim = ZIM.geInstance();

const VideoCalling = (props) => {
    // const zim = ZIM.geInstance();
    useEffect(() => {
        try {
            // ZIM.caller({ appID: '177503827', appSign: '4813ca648e686180b2d6e12956bf6ba8465112251090af88228754356c3939b1' });
        } catch (error) {
            console.log(error)
        }
    }, [])
    const [userInfo, setUserInfo] = useState({
        userID: '', //
        userName: '',
        token: ''
    })
    const [state, setState] = useState({
        message: '',
        otherUserId: ''
    })

    useEffect(() => {
        // Set up and listen for the callback for receiving error codes.  
        zim.on('error', function (zim, errorInfo) {
            console.log('error', errorInfo.code, errorInfo.message);
        });

        // Set up and listen for the callback for connection status changes. 
        zim.on('connectionStateChanged', function (zim, { state, event, extendedData }) {
            console.log('connectionStateChanged', state, event, extendedData);
        });

        // Set up and listen for the callback for receiving one-to-one messages. 
        zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
            console.log('receivePeerMessage', messageList, fromConversationID);
        });

        return () => {
            zim.logout();
            zim.destroy();
        }
    }, [])

    const handleLogin = () => {
        try {
            zim.login(userInfo, token)
                .then(function () {
                    // Login successful.
                })
                .catch(function (err) {
                    // Login failed.
                });
        } catch (error) {

        }
    }

    const sendMessage = () => {
        try {
            const messageTextObj = { type: 1, message: state.message };
            zim.sendMessage(messageTextObj, toUserID)
                .then(function ({ message }) {
                    // Message sent successfully.
                })
                .catch(function (err) {
                    // Failed to send the message.
                });
        } catch (error) {

        }
    }

    const onStateHandleChange = (key, value) => {
        setState({ ...state, [key]: value })
    }
    const onUserObjHandleChange = (key, value) => {
        setUserInfo({ ...state, [key]: value })
    }

    return (
        <View style={{ padding: 5 }}>
            <View>
                <View style={{ paddingVertical: 5 }}>
                    <Text>UserID</Text>
                    <TextInput
                        value={userInfo.userID}
                        onChangeText={(value) =>
                            onUserObjHandleChange('userID', value)}
                        style={{ borderWidth: 1 }} />
                </View>
                <View style={{ paddingVertical: 5 }}>
                    <Text>User Name</Text>
                    <TextInput
                        value={userInfo.userName}
                        onChangeText={(value) =>
                            onUserObjHandleChange('userName', value)}
                        style={{ borderWidth: 1 }} />
                </View>
                <View style={{ paddingVertical: 5 }}>
                    <Text>Token</Text>
                    <TextInput
                        value={userInfo.token}
                        onChangeText={(value) =>
                            onUserObjHandleChange('token', value)}
                        style={{ borderWidth: 1 }} />
                </View>
                <Button title="Login" onPress={handleLogin} />
                <View>
                    <View style={{ paddingVertical: 5 }}>
                        <Text>Other person ID</Text>
                        <TextInput
                            value={state.otherUserId}
                            onChangeText={(value) =>
                                onStateHandleChange('otherUserId', value)}
                            style={{ borderWidth: 1 }} />
                    </View>
                    <Button title="Submit" />
                </View>
                <View>
                    <View style={{ paddingVertical: 5 }}>
                        <Text>Message</Text>
                        <TextInput
                            value={state.message}
                            onChangeText={(value) =>
                                onStateHandleChange('message', value)}
                            style={{ borderWidth: 1 }} />
                    </View>
                    <Button title="Send" onPress={sendMessage} />
                </View>
            </View>
        </View>
    );
}

export default VideoCalling;
```

### Links:
[React Native In-App chatting Doc](https://docs.zegocloud.com/article/14692)
[Sample Codebase](https://docs.zegocloud.com/article/14697)

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/md4qqehqr5vth2t17jof.jpg)
![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cuypq8f84q8fa96yryhu.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wqm16t4fcq8cucynav1k.jpg)