Not all do! Some have four. Some have six but only use four regularly for locomotion.
The likely answer to your question is that six legs is not better or worse than four legs (depending on the type of locomotion) but instead that both are close enough to the optimal functional performance level that there's no selective pressure to have one or the other. In other words, having some legs helps dramatically with terrestrial locomotion, but there's no extra fitness cost associated with straying one or two legs away from that optimal number. It's much more likely that the first insects had six legs and so all their descendants have six legs, and that the first tetrapods had four limbs and so all their descendants have four limbs. Obviously, some lineages continued to diversify and adapt after this point in time, which is why you see variation today in both leg and limb number within these groups.
Evolution typically doesn't select for optimal but instead removes "not good enough" traits. Instead of asking "Why?", ask "Why not?"