Mine did a lot of this. The best thing is to distract them with something else. Luckily mine was ok with me hugging him so I just hugged him and just held him until he calmed down, I didnt speak, just held him and sometimes hummed mellow nursery rhymes. When they're in a state they cant register anything so asking questions and talking to them adds to the stress they're feeling. It's important to acknowledge their feels afterwards and explain to them what they were feeling (depending on their age they just feel stuff but don't understand what it is). I also use to show him deep breathing and eventually he use to copy me which helped calm him quicker. When he got older (2 yo ish) he also went through a phase where it seemed he was doing it on purpose and for attention. I was told by people to ignore it. I did but always talked it through with him after. He soon stopped. Its the whole don't reward/give attention to bad behaviour. But u need to try different techniques for different ages.
I come from an Eastern European family, and have a 10 year younger brother. First time I saw this behaviour was with him. He was banging his head on the floor very hard, my mom got scared and went to the doctor. The doctor chuckled and said it’s my mom who needed treatment 😂. She recommended that whenever my brother does this, she removes herself from the room. This led to my brother then following my mom in different rooms to bang his head wherever she was. But she would calmly “not address this behaviour”/ aka ignore it and move to another room. In time, it stopped because he understanding he wasn’t getting any attention from this behaviour.
I would say something like ‘if we bang our head it hurts, ouchie’ then distract with an activity x