How is the head of dynasty decided?
Solution 1:
I stumbled upon this entry from the CKIII FAQ posted by Paradox themselves:
Q: I understand that the head of the most powerful house head becomes the head of the dynasty, but what determines who is the most powerful house head? Which factors are the most relevant?
A: Military strength is the main factor
But it appears that when the head of the dynasty dies, then the new head is determined before the titles of the old head get passed on the heirs. As your primary heir will usually not have that many titles and vassals at that point, the head of the house title will often pass on to a different ruler of your dynasty.
Fortunately, that's only temporary. A couple months later, the game will reevaluate the military strength of all dynasty members, see that your character now has all those troops from the inherited titles and vassals, and give the head position to the now strongest character (you).
Solution 2:
Another thing to consider here is that only house heads can become dynasty heads. House Head is directly inherited by the primary heir (i.e. usually your oldest son/child), even if you use elective succession to make another child your heir.
So, when you die, check whether your heir is the house head, if not, you must make a new cadet branch to become eligible to become dynasty head again.