Deductions & credits

They are separate transactions so no, you can’t avoid the gain by buying another property unless you are dealing with rental property and a 1031 exchange.