npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mqtt-react-hooks

v3.1.0

Published

ReactJS library for Pub/Sub communication with an MQTT broker using Hooks

Readme

npm Quality and Build

Overview

A note from the author: Sorry for the lack of updates since 2021! I originally built this library for my graduation project when I was very new to programming. Today, with a deeper understanding and far better tools, I've finally come back to fix everything and transform this into the library it was always meant to be. Thank you for your patience!

This library is focused in help you to connect, publish and subscribe to a Message Queuing Telemetry Transport (MQTT) in ReactJS with the power of React Hooks.

🚀 Version 3.0.0 - Major Architecture Rewrite!

Version 3.0.0 introduces a globally scalable SubscriptionManager multiplexer.

  • Zero Event Duplication: Calling useSubscription inside multiple nested components no longer spawns duplicate client.on('message') listeners. Everything routes perfectly through a single Singleton-Context listener.
  • Intelligent Reference Counting: The broker only .subscribes over the network on the first mount. When the very last matching hook unmounts, it safely triggers .unsubscribe().
  • Pre-Hydrated Cache: If a sensor event occurs and a React hook mounts a few seconds later, it instantly loads the cached payload.
  • Upgraded Core: Powered natively by the highly robust latest mqtt v5 implementation.

Installation

Just add mqtt-react-hooks and mqtt to your project:

npm add mqtt-react-hooks mqtt

Exported Hooks

  • useMqttState -> returns { connectionStatus, client, message }
  • useSubscription(topic: string | string[], options?: {} ) -> returns { client, topic, message, connectionStatus }

Usage

Similarly to react-redux, you must first wrap your application (or subtree) with a <Connector> which will initialize the internal Mqtt Client instance and Subscription Multiplexer.

Root component

The only required prop is brokerUrl. Additional options follow the standard mqtt.Client#connect schema.

import React from 'react';
import { Connector } from 'mqtt-react-hooks';
import Status from './Status';

export default function App() {
  return (
    <Connector brokerUrl="wss://test.mosquitto.org:8081/mqtt">
      <Status />
    </Connector>
  );
}

Connection Status

Use useMqttState to universally extract the internal connection variables safely without subscribing to topics.

import React from 'react';
import { useMqttState } from 'mqtt-react-hooks';

export default function Status() {
  /*
   * Status strings:
   * - Connecting
   * - Connected
   * - Reconnecting
   * - Offline
   * - Error
   */
  const { connectionStatus } = useMqttState();

  return <h1>{`Status: ${connectionStatus}`}</h1>;
}

Subscribing to Overlapping Topics

Multiple components can subscribe directly to arrays or exact wildcard filters independently without clashing.

import React from 'react';
import { useSubscription } from 'mqtt-react-hooks';

export default function RoomGauges() {
  /* Message structure:
   *  topic: string
   *  message: string (or Buffer depending on parser)
   */
  const { message } = useSubscription([
    'room/livingroom/temperature',
    'room/kitchen/temperature',
  ]);

  return (
    <div>
      <span>Latest Update: {message?.topic}</span>
      <h2>{message?.message}°C</h2>
    </div>
  );
}

Publishing Messages

You don't need a topic subscription if you just want to publish! You can use useMqttState (or pass an empty array to useSubscription([])) to just grab the raw client object:

import React from 'react';
import { useSubscription } from 'mqtt-react-hooks';

export default function SwitchButton() {
  const { client } = useSubscription([]);

  function handleClick() {
    client?.publish('room/livingroom/lights', 'OFF');
  }

  return (
    <button type="button" onClick={handleClick}>
      Disable Lights
    </button>
  );
}

Tips

Bundler Troubleshooting (Vite / Webpack)

If your specific bundler configuration struggles to resolve Node-specific modules (like Buffer or process) natively, or if you run into strict ESM resolution errors, check out the MQTT.js Bundle documentation. MQTT.js provides pre-built browser-optimized distributions (e.g., mqtt/dist/mqtt.min) which you can alias or import directly if needed.

Contributing

Thanks for being interested on making this package better. We encourage everyone to help improving this project with some new features, bug fixes and performance issues. Please take a little bit of your time to read our guides, so this process can be faster and easier.

License

MIT ©