There's no way to avoid a bad beat, It's part of the game. The 1 million questions is; How to accept a bad beat.
You just need to realize that as long as they have outs, they can win. Like it's just as simple as that, it really is. You know you have the best hand but every time before calling you must realize you're not calling to win it automatically, you're calling the percentages that favor you, however, those percentages can shift. It's the fundamental value of poker.
Everybody remembers the bad beats but none remembers the revered quads, the 1-outers that hit on the river. So try and go back to those moments you yourself hit that 1-outer when you were almost drawing dead and remember that's what the game is built on - not only skill but luck also.