When freediving, you can't really avoid it. What you learn however is how to deal with it. Control your diaphragm when it wants to start breathing, as the spasms are wasted energy. It's mostly a mind thing. With simple exercises (co2 tables) and just getting used to the feeling, it took my quite a short time to reach 5 minutes.
One "trick" btw is hyper ventilating. But DONT DO IT! It get rids of lots of co2 in your blood stream / lungs, so it takes a bit longer for the co2 buildup. But you need that buildup. Even though it's painful, that's your only signal as to how you're doing and which you kinda calibrate against. Especially when diving, hyper ventilating before can make it so you suddenly go unconscious before you felt the urge to surface.