Historically, and in many denominations still today, it is considered disrespectful for men to wear hats in church. This tradition stems from the idea that men should remove their hats as a sign of respect before God, similar to how one might remove their hat when entering someone's home.
However, cultural norms and church practices can vary. Some churches may be more relaxed about this tradition, and in certain situations, such as medical reasons or religious head coverings, hats may be permitted or even required.
Ultimately, the best course of action is to be aware of the specific customs of the church you are attending and to err on the side of respect. If you are unsure, it is always polite to remove your hat or ask an usher for clarification.