{"id":15063394,"url":"https://github.com/victorhas/mqtt-react-hooks","last_synced_at":"2026-05-02T03:32:25.553Z","repository":{"id":38172744,"uuid":"238828575","full_name":"VictorHAS/mqtt-react-hooks","owner":"VictorHAS","description":"ReactJS library for Pub/Sub communication with an MQTT broker using Hooks","archived":true,"fork":false,"pushed_at":"2023-02-04T11:50:26.000Z","size":1719,"stargazers_count":92,"open_issues_count":32,"forks_count":28,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-12-14T13:36:43.160Z","etag":null,"topics":["hooks","mqtt","mqtt-broker","mqtt-react-hooks","reactjs","topic"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/VictorHAS.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.MD","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null}},"created_at":"2020-02-07T02:34:39.000Z","updated_at":"2024-11-23T15:42:27.000Z","dependencies_parsed_at":"2023-02-08T18:01:39.841Z","dependency_job_id":null,"html_url":"https://github.com/VictorHAS/mqtt-react-hooks","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VictorHAS%2Fmqtt-react-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VictorHAS%2Fmqtt-react-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VictorHAS%2Fmqtt-react-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VictorHAS%2Fmqtt-react-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/VictorHAS","download_url":"https://codeload.github.com/VictorHAS/mqtt-react-hooks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235356073,"owners_count":18976818,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hooks","mqtt","mqtt-broker","mqtt-react-hooks","reactjs","topic"],"created_at":"2024-09-24T23:56:01.582Z","updated_at":"2026-05-02T03:32:25.506Z","avatar_url":"https://github.com/VictorHAS.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n[![npm](https://img.shields.io/npm/v/mqtt-react-hooks?color=blue)](https://www.npmjs.com/package/mqtt-react-hooks)\u003cspace\u003e\u003cspace\u003e\n[![Quality and Build](https://github.com/VictorHAS/mqtt-react-hooks/actions/workflows/publish.yml/badge.svg)](https://github.com/VictorHAS/mqtt-react-hooks/actions/workflows/publish.yml)\n\n\u003c/div\u003e\n\n## Overview\n\n\u003e **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!\n\nThis 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.\n\n## 🚀 Version 3.0.0 - Major Architecture Rewrite!\nVersion `3.0.0` introduces a globally scalable **SubscriptionManager multiplexer**.\n\n* **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.\n* **Intelligent Reference Counting**: The broker only `.subscribe`s over the network on the first mount. When the very last matching hook unmounts, it safely triggers `.unsubscribe()`.\n* **Pre-Hydrated Cache**: If a sensor event occurs and a React hook mounts a few seconds later, it instantly loads the *cached payload*.\n* **Upgraded Core**: Powered natively by the highly robust latest `mqtt` v5 implementation.\n\n## Installation\n\nJust add `mqtt-react-hooks` and `mqtt` to your project:\n\n```bash\nnpm add mqtt-react-hooks mqtt\n```\n\n### Exported Hooks\n\n- `useMqttState` -\u003e returns `{ connectionStatus, client, message }`\n- `useSubscription(topic: string | string[], options?: {} )` -\u003e returns `{ client, topic, message, connectionStatus }`\n\n---\n\n## Usage\n\nSimilarly to `react-redux`, you must first wrap your application (or subtree) with a `\u003cConnector\u003e` which will initialize the internal Mqtt Client instance and Subscription Multiplexer.\n\n### Root component\n\nThe only required prop is `brokerUrl`. Additional options follow the standard [mqtt.Client#connect](https://github.com/mqttjs/MQTT.js#connect) schema.\n\n```tsx\nimport React from 'react';\nimport { Connector } from 'mqtt-react-hooks';\nimport Status from './Status';\n\nexport default function App() {\n  return (\n    \u003cConnector brokerUrl=\"wss://test.mosquitto.org:8081/mqtt\"\u003e\n      \u003cStatus /\u003e\n    \u003c/Connector\u003e\n  );\n}\n```\n\n### Connection Status\n\nUse `useMqttState` to universally extract the internal connection variables safely without subscribing to topics.\n\n```tsx\nimport React from 'react';\nimport { useMqttState } from 'mqtt-react-hooks';\n\nexport default function Status() {\n  /*\n   * Status strings:\n   * - Connecting\n   * - Connected\n   * - Reconnecting\n   * - Offline\n   * - Error\n   */\n  const { connectionStatus } = useMqttState();\n\n  return \u003ch1\u003e{`Status: ${connectionStatus}`}\u003c/h1\u003e;\n}\n```\n\n### Subscribing to Overlapping Topics\n\n Multiple components can subscribe directly to arrays or exact wildcard filters independently without clashing.\n\n```tsx\nimport React from 'react';\nimport { useSubscription } from 'mqtt-react-hooks';\n\nexport default function RoomGauges() {\n  /* Message structure:\n   *  topic: string\n   *  message: string (or Buffer depending on parser)\n   */\n  const { message } = useSubscription([\n    'room/livingroom/temperature',\n    'room/kitchen/temperature',\n  ]);\n\n  return (\n    \u003cdiv\u003e\n      \u003cspan\u003eLatest Update: {message?.topic}\u003c/span\u003e\n      \u003ch2\u003e{message?.message}°C\u003c/h2\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### Publishing Messages\n\nYou 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:\n\n```tsx\nimport React from 'react';\nimport { useSubscription } from 'mqtt-react-hooks';\n\nexport default function SwitchButton() {\n  const { client } = useSubscription([]);\n\n  function handleClick() {\n    client?.publish('room/livingroom/lights', 'OFF');\n  }\n\n  return (\n    \u003cbutton type=\"button\" onClick={handleClick}\u003e\n      Disable Lights\n    \u003c/button\u003e\n  );\n}\n```\n\n## Tips\n\n### Bundler Troubleshooting (Vite / Webpack)\n\nIf 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](https://github.com/mqttjs/MQTT.js#bundle). MQTT.js provides pre-built browser-optimized distributions (e.g., `mqtt/dist/mqtt.min`) which you can alias or import directly if needed.\n\n## Contributing\n\nThanks 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.\n\n## License\n\nMIT ©\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvictorhas%2Fmqtt-react-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvictorhas%2Fmqtt-react-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvictorhas%2Fmqtt-react-hooks/lists"}