Skip to content

ESP32 MQTT Reconnection After Wi-Fi Drop Never Works

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about ESP32 MQTT Reconnection After Wi. We cover key concepts, practical examples, and best practices.

The Problem

ESP32 loses Wi-Fi and MQTT connection drops. Reconnection logic runs but never reconnects.

Quick Fix

Wrong

if (!client.connected()) { client.connect("esp32"); }
MQTT reconnection fails indefinitely. Device stays offline.
void reconnect() {
  while (!client.connected()) {
    if (WiFi.status() == WL_CONNECTED) {
      if (client.connect("esp32-reconnect")) {
        client.subscribe("sensor/cmd");
      }
    } else { WiFi.reconnect(); }
    delay(5000);
  }
}
void loop() {
  if (!client.connected()) reconnect();
  client.loop();
}
Reconnecting...
Wi-Fi reconnected. MQTT reconnected.

Prevention

Check Wi-Fi status before MQTT reconnect. Resubscribe to all topics after reconnection. Call client.loop() regularly. Maintain a list of subscribed topics. Use a flag to prevent reconnection loops.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Do I need to resubscribe after reconnection?

Yes. MQTT subscriptions are lost when the connection drops. Maintain a list of topics and resubscribe after every successful reconnect.

How do I detect MQTT disconnection?

Check client.connected() in loop(), or register a callback with client.setCallback() for unexpected disconnections.

Should I clear the MQTT queue on reconnect?

Yes. Call client.disconnect() before reconnecting to clear pending messages from the old session.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro