I looked it up in Quinion:

It comes from the English game of cricket and refers to a bowler who
takes three wickets with three successive balls. For those more familiar
with baseball, this is an impressive achievement, similar to a baseball
pitcher striking out three batters in a row, but much less common. It seems
to have been the custom in the nineteenth century for such a paragon of the
art to be awarded a new hat by his club as a mark of his success.
However, it is sometimes also said that the phrase alludes to a distinctly
more plebeian reward in which the bowler was permitted to take his hat
around the crowd for a collection (not necessarily a bowler hat, of course:
that was named after a couple of completely different chaps, Messrs
Thomas and William Bowler, hatmakers). Hat trick was first recorded in
print in the 1870s, but has since been widened to apply to any sport in
which the person competing carries off some feat three times in quick
succession, such as scoring three goals in one game of soccer.