How to use MQTT in the React project

React (also known as React.js or ReactJS) is an open-source, front end, JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications. However, React is only concerned with rendering data to the DOM, and so creating React applications usually requires the use of additional libraries for state management and routing. Redux and React Router are respective examples of such libraries.1

This article mainly introduces how to use MQTT in the React project for implementing connect, subscribe, messaging and unsubscribe, etc., between the client and MQTT broker.

Project initialisation

New project

Reference link:

  • Creating new React applications with Create React App

    npx create-react-app react-mqtt-test

    If you need to use TypeScript, simply add the --template typescript parameter at the end of the command line

    npx create-react-app react-mqtt-test --template typescript

    Then add the TypeScript type library required in the React project

    npm install --save typescript @types/node @types/react @types/react-dom @types/jest
    # or
    yarn add typescript @types/node @types/react @types/react-dom @types/jest

    The use of TypeScript will not be the focus of the examples in this article, but if you wish to use it, you can add TypeScript features after referring to the creation example and the full code examples.

  • Import via CDN

    <script crossorigin src=""></script>
    <script crossorigin src=""></script>

Install the MQTT client library

As React is a JavaScript library, it is possible to use MQTT.js as the MQTT client library.

The following methods 2, 3 are more suitable for referencing projects created by React via CDN links.

  1. Installation via the command line, either using the npm or yarn command (one or the other)

    npm install mqtt --save
    # or
    yarn add mqtt
  2. Import via CDN

    <script src=""></script>
  3. Download to the local and then import using the relative path

    <script src="/your/path/to/mqtt.min.js"></script>

The use of MQTT

Connect the MQTT broker

This article will use the free public MQTT broker which is provided by EMQ X. This service is based on EMQ X's MQTT IoT cloud platform to create. The server access information is as follows.

  • Broker:
  • TCP Port: 1883
  • Websocket Port: 8083


const [client, setClient] = useState(null);
const mqttConnect = (host, mqttOption) => {
  setClient(mqtt.connect(host, mqttOption));
useEffect(() => {
  if (client) {
    client.on('connect', () => {
    client.on('error', (err) => {
      console.error('Connection error: ', err);
    client.on('reconnect', () => {
    client.on('message', (topic, message) => {
      const payload = { topic, message: message.toString() };
}, [client]);


const mqttSub = (subscription) => {
  if (client) {
    const { topic, qos } = subscription;
    client.subscribe(topic, { qos }, (error) => {
      if (error) {
        console.log('Subscribe to topics error', error)


const mqttUnSub = (subscription) => {
  if (client) {
    const { topic } = subscription;
    client.unsubscribe(topic, error => {
      if (error) {
        console.log('Unsubscribe error', error)


const mqttPublish = (context) => {
  if (client) {
    const { topic, qos, payload } = context;
    client.publish(topic, payload, { qos }, error => {
      if (error) {
        console.log('Publish error: ', error);


const mqttDisconnect = () => {
  if (client) {
    client.end(() => {


We have written the following simple browser application using React with the ability to create connections, subscribe to topics, send and receive messages, unsubscribe, and disconnect.

The complete project example code:


Use MQTT 5.0 client tool - MQTT X as another client to test sending and receiving messages.


You can see that MQTT X can receive messages from the browser side normally, as can be seen when sending a message to the topic using MQTT X.



In summary, we have implemented the creation of an MQTT connection in the React project, and simulated subscribing, sending and receiving messages, unsubscribing and disconnecting between the client and MQTT broker.

In this article, we use React v16.13.1, so the Hook Component feature will be used as example code to demonstrate, or if required, you can refer to the ClassMqtt component in the full example code to use the Class Component feature for project building.

Shifan Yu

Shifan Yu

EMQ X software engineer, responsible for the front-end development of EMQ X, is also the developer and maintainer of MQTT X.

The streaming database built for IoT data storage and real-time processing.

Fully managed MQTT 5.0 IoT cloud, start a 180-day free trial.

Related Links

MQTT X v1.3.0 was officially released - Cross-platform MQTT 5.0 desktop test client

[MQTT X]( is a cross-platform MQTT 5.0 desktop test client provided by the world's leading open source IoT middleware provider [EMQ]( , which supports macOS, Linux, Windows. The user interface of **MQTT X** simplifies the operation logic of the page with the pattern of chatting software. Users can quickly create multiple simultaneous-online MQTT clients to test the connection/publish/subscribe functions of MQTT/TCP, MQTT/TLS and other MQTT protocol features.

A「date」between MQTT and CoAP in the EMQ X world

This article will show you a「date」between MQTT client and CoAP client in the EMQ X world.

Remote control LED with ESP8266 and MQTT

In this project, we will implement remote control LED lights via NodeMCU(ESP8266) and MQTT broker, and use the Arduino IDE to program NodeMCU ESP8266.