Restoring to factury state normally means you don’t have all security patches installed, no firewall etc. That means you go online unprotected and that is how you got infected again.

After a clean installation always install a firewall and av software before going online. Then get ALL security patches/updates.