Mostly the two are less connected than people hope. In the majority of countries, simply buying a home gives you no visa or residency rights at all; you can own the property but still need to qualify for entry and stay like any other foreigner. The exceptions are formal golden visa or investor residency programs, where a qualifying property purchase above a set threshold is an explicit route to a residence permit, though several countries have tightened or scrapped these schemes, so verify current rules officially.
In the other direction, losing your visa or residency generally does not force you to sell. Property rights and immigration status are separate legal tracks in most places, so you can keep, rent out, or sell the home from abroad, though remote management and non-resident tax treatment become the practical headaches.
A few countries do tie certain ownership categories to residency status, so before buying, ask a local property lawyer specifically what happens to your title if your immigration status changes.