video sdk logo

Login

React Video Calling Tutorial

Add real-time 1:1 and group video calling to any web app. Adaptive bitrate keeps calls smooth across changing network conditions, with simulcast and active-speaker detection built in.
React Video Calling Tutorial

Trusted by 300+ global business & tech leaders

Build a Video Call App in React, Step by Step

Learn how to add video calling to a React app using the VideoSDK React SDK. This step-by-step tutorial takes you from a blank React project to a working video call with camera, microphone, screen-share, and leave controls.


Prerequisites

Before proceeding, ensure that your development environment meets the following requirements:

  • VideoSDK Developer Account (Not having one, follow VideoSDK Dashboard)
  • Basic understanding of React
  • React VideoSDK
  • Have Node and NPM installed on your device.
  • Basic understanding of Hooks (useState, useRef, useEffect)
  • React Context API (optional)

Important: One should have a VideoSDK account to generate token. Visit VideoSDK dashboard to generate token

Getting Started with the Code!

Follow the steps to create the environment necessary to add video calls into your app. You can also find the code sample for quickstart here.

Create new React App

Create a new React App using the below command.

Terminal
1npm create vite@latest videosdk-rtc-react-app -- --template react
2

Install VideoSDK

Install the VideoSDK using the below-mentioned npm command. Make sure you are in your react app directory before you run this command.

NPM
1npm install "@videosdk.live/react-sdk"
2
Yarn
1yarn add "@videosdk.live/react-sdk"
2

Structure of the project

Your project structure should look like this.

Project Structure
1   root
2   ├── node_modules
3   ├── public
4   ├── src
5   │    ├── API.js
6   │    ├── App.jsx
7   │    ├── main.jsx
8   .    .
9

You are going to use functional components to leverage react's reusable component architecture. There will be components for users, videos and controls (mic, camera, leave) over the video.

App Architecture

The App will contain a MeetingView component which includes a ParticipantView component which will render the participant's name, video, audio, etc. It will also have a Controls component which will allow the user to perform operations like leave and toggle media.

VideoSDK React JS Quick Start Architecture

You will be working on the following files:

  • API.js: Responsible for handling API calls such as generating unique meetingId and token
  • App.jsx: Responsible for rendering MeetingView and joining the meeting.

Step 1: Get started with API.js

Prior to moving on, you must create an API request to generate a unique meetingId. You will need an authentication token, which you can create either through the videosdk-rtc-api-server-examples or directly from the VideoSDK Dashboard for developers.

API.js (Javascript)
1// Generate your token at https://app.videosdk.live/api-keys and paste it below.
2export const authToken = "";
3
4// API call to create meeting
5export const createMeeting = async ({ token }) => {
6  try {
7    const res = await fetch(`https://api.videosdk.live/v2/rooms`, {
8      method: "POST",
9      headers: {
10        authorization: `${token}`,
11        "Content-Type": "application/json",
12      },
13      body: JSON.stringify({}),
14    });
15
16    if (!res.ok) {
17      throw new Error(`Failed to create meeting: ${res.status}`);
18    }
19
20    //Destructuring the roomId from the response
21    const { roomId } = await res.json();
22    return roomId;
23  } catch (error) {
24    console.error("createMeeting failed", error);
25    throw error;
26  }
27};
28

Step 2: Wireframe App.jsx with all the components

To build up wireframe of App.jsx, you need to use VideoSDK Hooks and Context Providers. VideoSDK provides MeetingProvider, MeetingConsumer, useMeeting and useParticipant hooks.

First you need to understand Context Provider and Consumer. Context is primarily used when some data needs to be accessible by many components at different nesting levels.

  • MeetingProvider: This is the Context Provider. It accepts value config and token as props. The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
  • MeetingConsumer: This is the Context Consumer. All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
  • useMeeting: This is the meeting hook API. It includes all the information related to meeting such as join, leave, enable/disable mic or webcam etc.
  • useParticipant: This is the participant hook API. It is responsible for handling all the events and props related to one particular participant such as name, webcamStream, micStream etc.

The Meeting Context provides a way to listen for any changes that occur when a participant joins the meeting or makes modifications to their microphone, camera, and other settings. Begin by making a few changes to the code in the App.jsx file.

App.jsx (Javascript)
1import "./App.css";
2import React, { useEffect, useRef, useState } from "react";
3import {
4  MeetingProvider,
5  MeetingConsumer,
6  useMeeting,
7  useParticipant,
8  VideoPlayer,
9} from "@videosdk.live/react-sdk";
10import { authToken, createMeeting } from "./API";
11
12function JoinScreen({ getMeetingAndToken }) {
13  return null;
14}
15
16function ParticipantView(props) {
17  return null;
18}
19
20function Controls(props) {
21  return null;
22}
23
24function MeetingView(props) {
25  return null;
26}
27
28function App() {
29  const [meetingId, setMeetingId] = useState(null);
30
31  //Getting the meeting id by calling the api we just wrote
32  const getMeetingAndToken = async (id) => {
33    if (!authToken) {
34      console.error("PLEASE PROVIDE TOKEN IN API.js FROM app.videosdk.live");
35      return;
36    }
37    const meetingId =
38      id == null ? await createMeeting({ token: authToken }) : id;
39    setMeetingId(meetingId);
40  };
41
42  //This will set Meeting Id to null when meeting is left or ended
43  const onMeetingLeave = () => {
44    setMeetingId(null);
45  };
46
47  return authToken && meetingId ? (
48    <MeetingProvider
49      config={{
50        meetingId,
51        micEnabled: true,
52        webcamEnabled: true,
53        name: "C.V. Raman",
54      }}
55      token={authToken}
56    >
57      <MeetingConsumer>
58        {() => (
59          <MeetingView meetingId={meetingId} onMeetingLeave={onMeetingLeave} />
60        )}
61      </MeetingConsumer>
62    </MeetingProvider>
63  ) : (
64    <JoinScreen getMeetingAndToken={getMeetingAndToken} />
65  );
66}
67
68export default App;
69

Step 3: Implement Join Screen

Join screen will serve as a medium to either schedule a new meeting or join an existing one.

JoinScreen Component (Javascript)
1function JoinScreen({ getMeetingAndToken }) {
2  const [meetingId, setMeetingId] = useState(null);
3  const onClick = async () => {
4    await getMeetingAndToken(meetingId);
5  };
6  return (
7    <div>
8      <input
9        type="text"
10        placeholder="Enter Meeting Id"
11        onChange={(e) => {
12          setMeetingId(e.target.value);
13        }}
14      />
15      <button onClick={onClick}>Join</button>
16      {" or "}
17      <button onClick={onClick}>Create Meeting</button>
18    </div>
19  );
20}
21

Output

VideoSDK React JS Quick Start Join Screen

Step 4: Implement MeetingView and Controls

Next step is to create MeetingView and Controls components to manage features such as join, leave, mute and unmute.

From v1.0.0, all these methods are asynchronous and return a Promise, so awaitthem and handle failures with try / catch. For details, see the Migration Guide.

MeetingView (Javascript)
1function MeetingView(props) {
2  const [joined, setJoined] = useState(null);
3  //Get the method which will be used to join the meeting.
4  //We will also get the participants list to display all participants
5  const { join, participants } = useMeeting({
6    //callback for when meeting is joined successfully
7    onMeetingJoined: () => {
8      setJoined("JOINED");
9    },
10    //callback for when meeting is left
11    onMeetingLeft: () => {
12      props.onMeetingLeave();
13    },
14  });
15  const joinMeeting = async () => {
16    setJoined("JOINING");
17    try {
18      await join();
19    } catch (error) {
20      console.error("Failed to join meeting", error);
21      setJoined(null);
22    }
23  };
24
25  return (
26    <div className="container">
27      <h3>Meeting Id: {props.meetingId}</h3>
28      {joined && joined == "JOINED" ? (
29        <div>
30          <Controls />
31          //For rendering all the participants in the meeting
32          {[...participants.keys()].map((participantId) => (
33            <ParticipantView
34              participantId={participantId}
35              key={participantId}
36            />
37          ))}
38        </div>
39      ) : joined && joined == "JOINING" ? (
40        <p>Joining the meeting...</p>
41      ) : (
42        <button onClick={joinMeeting}>Join</button>
43      )}
44    </div>
45  );
46}
47
Controls Component (Javascript)
1function Controls() {
2  const { leave, toggleMic, toggleWebcam } = useMeeting();
3
4  const handleLeave = async () => {
5    try {
6      await leave();
7    } catch (error) {
8      console.error("Failed to leave meeting", error);
9    }
10  };
11
12  const handleToggleMic = async () => {
13    try {
14      await toggleMic();
15    } catch (error) {
16      console.error("Failed to toggle mic", error);
17    }
18  };
19
20  const handleToggleWebcam = async () => {
21    try {
22      await toggleWebcam();
23    } catch (error) {
24      console.error("Failed to toggle webcam", error);
25    }
26  };
27
28  return (
29    <div>
30      <button onClick={handleLeave}>Leave</button>
31      <button onClick={handleToggleMic}>toggleMic</button>
32      <button onClick={handleToggleWebcam}>toggleWebcam</button>
33    </div>
34  );
35}
36

Output of Controls Component

VideoSDK React JS Quick Start  Controls Component

Step 5: Implement Participant View

Before implementing the participant view, you need to understand a couple of concepts.

1. Forwarding Ref for mic

The useRef hook is responsible for referencing the audio component. It will be used to play and stop the audio of the participant.

Forwarding Ref for mic
1const micRef = useRef(null);
2

2. useParticipant Hook

The useParticipant hook is responsible for handling all the properties and events of one particular participant joined in the meeting. It will take participantId as argument.

useParticipant Hook
1const { micStream, webcamOn, micOn } = useParticipant(props.participantId);
2

3. MediaStream API

The MediaStream API is beneficial for adding a MediaTrack to the audio tag, enabling the playback of audio.

MediaStream API
1const micRef = useRef(null);
2const mediaStream = new MediaStream();
3mediaStream.addTrack(micStream.track);
4
5micRef.current.srcObject = mediaStream;
6micRef.current
7  .play()
8  .catch((error) => console.error("micElem.current.play() failed", error));
9

Note: Only use the MediaStream API for microphone access. The VideoPlayer component in VideoSDK automatically handles the video stream.

Now you can use both of the hooks and the API to create ParticipantView

ParticipantView (Javascript)
1function ParticipantView(props) {
2  const micRef = useRef(null);
3  const { micStream, webcamOn, micOn, isLocal, displayName } = useParticipant(
4    props.participantId
5  );
6
7  useEffect(() => {
8    if (micRef.current) {
9      if (micOn && micStream) {
10        const mediaStream = new MediaStream();
11        mediaStream.addTrack(micStream.track);
12
13        micRef.current.srcObject = mediaStream;
14        micRef.current
15          .play()
16          .catch((error) =>
17            console.error("micElem.current.play() failed", error)
18          );
19      } else {
20        micRef.current.srcObject = null;
21      }
22    }
23  }, [micStream, micOn]);
24
25  return (
26    <div>
27      <p>
28        Participant: {displayName} | Webcam: {webcamOn ? "ON" : "OFF"} | Mic:{" "}
29        {micOn ? "ON" : "OFF"}
30      </p>
31      <audio ref={micRef} autoPlay muted={isLocal} />
32      {webcamOn && (
33        <VideoPlayer
34          participantId={props.participantId} // Required
35          type="video" // "video" or "share"
36          containerStyle={{
37            height: "200px",
38            width: "300px",
39          }}
40          className="h-full"
41          classNameVideo="h-full"
42          videoStyle={{}}
43        />
44      )}
45    </div>
46  );
47}
48

Final Output

You have completed the implementation of a customized video calling app in React.js using VideoSDK. To explore more features, go through Basic and Advanced features.

Tip: You can checkout the complete quick start example here.

Summarize with

ChatGPTClaudePerplexityGoogleGrok
Prefer VideoSDK on Google

Table of Contents

Start Building Now With $20 Free Balance

No credit card required to start.

Documentation →Github Repo →

Share This Article

TwitterLinkedInFacebookHacker News

Get started for free today

Grab your API keys and start building with free $20 included in your account. Need enterprise-grade security or custom workloads? Talk to an expert!

Book a demo

Video SDK Logo

United States

28 Geary St, Suite 650,
San Francisco, CA 94108, United States

India flag

India

18th Floor, 1812, The Junomoneta Tower,
Adajan-Hazira Rd, Surat, Gujarat 395009, India

Video SDK Logo
Video SDK Logo
Video SDK Logo
Video SDK Logo
SOLUTIONS

Video KYC

Video Banking

Virtual Claim

Video MER

Telehealth

Astrology

Gaming

Dating

Live Commerce

Auto Proctoring

Interview-as-a-service

Virtual Events

Live Audio Streaming

Ed-Tech

PRODUCTS

AI-Agents

Real-time Audio & Video SDK

Interactive Live Streaming SDK

Real-time Transcription SDK

Character SDK

Open Source Examples

SUCCESS STORIES

Examedi

Coderschool

TYHO

ForagerOne

Immigo

DEVELOPERS

Documentation

Code Samples

Developer Updates

Developer Hub

TOP ARTICLES

What is WebRTC?

Build a React Native Video Calling App

Build a Flutter Video Calling App

RESOURCES

The Protocol by Video SDK

AI Apps

Creator Program

LEGAL

Terms Of Service

Privacy Policy

Cookie Notice

CCPA Notice

Subprocessors

DPA

RSS

COMPANY

Contact Us

Pricing

Support

Blog

Press Kit