Exactly when did Madara come back to life after his defeat by Hashirama?
Izanagi is a technique which is able to rewrite history. You take an event that wasn't favorable to you and make it into nothing more than a dream.

He set up Izanagi beforehand to be trigger a few hours after his death. Even though he was already dead, the technique still activated (Much like Itachi sealed his own Amaterasu into Sasuke's eye, and it activated even though Itachi already died).

Once Izanagi was activated, Madara's death was cancelled.