To be precise, for men in the US (and the UK, I believe) from the 1800s to 1950ish, hats were invariably to be worn outdoors but doffed indoors, among all classes. (There were exceptions. For example, it was OK for a man to wear a hat indoors when traversing a lobby or hallway, sometimes in an elevator, in large stores, et cetera.) Hat-wearing began to decline in the 1950s and sharply in the 1960s. (In my opinion John F. Kennedy's influence in this process is often mentioned but has been greatly overstated.)
I have no reliable knowledge of hat hair. Pomades like Brylcreem and Brillantine were much more common, men's hair was short and frequently cut, and I believe I've read that hair was washed much less often. I don't remember seeing hat-hair in movies, but that's not necessarily a reliable source (c.f. telephone conversations in movies). If I can be indulged in speculation, I suspect that it either wasn't a problem, or that men combed it or hand-adjusted it flat.
(I mention "men" specifically because, in traditional etiquette, a woman should wear a hat everywhere except in her own home, and could keep wearing it even when men would doff it, such as in a church, when seeing a funeral procession, during the National Anthem, et cetera.)
Am I missing anything in the AskHistorians FAQ? I would have sworn I had seen links there, but I can't find them in the fashion section.
There are a number of hits for "hats" in searching AskHistorians, though asking about the decline from the 1950s on seems to be a more common question. I have only skimmed these threads, so unfortunately I haven't done the curation work to offer this as an FAQ section. (And one isn't even a Reddit link.)