MQTT switch shows incorrect state when HASS restarts

I have a Sonoff Basic that is configured as a switch in my configuration.yaml:

mqtt:
  broker: 127.0.0.1
  port: 1883
  username: !secret mqtt_username
  password: !secret mqtt_password

switch:
  - platform: mqtt
    name: "Noahs Bedroom Fan"
    command_topic: "cmnd/sonoff05/power"
    state_topic: "stat/sonoff05/POWER"
    qos: 1
    payload_on: "ON"
    payload_off: "OFF"
    retain: true

It is usually on when I restart HA and it is depicted as off when HA restarts. I have other Sonoff-controlled lights that work as expected. If I set the switch to on in HA, it shows as on and the fan it controls continues to run. If I thn turn it off, the fan turns off and HA and the Sonoff are in sync from then on.
What process discovers the initial state of the switch? Is an MQTT status query sent to the fan? I think I know the answer as MQTT clients only broadcast messages and don’t repond to queries per se, right? Is the state saved somewhere across restarts? Is there something in my configuration that can lead to the problem?

Hi @mlefevre, take a look here.

That fixed it. Thanks for the help.