Explain like a finance expert , How does refinancing work?

I am looking to buy my first house and keep hearing "oh you can just refinance when rates come down". If refinancing into a lower rate saves you money, then someone else is losing money. Why is it allowed and how does it work?