In total there are 16 hats to unlock.
8 of the hats can be unlocked by any racer, but each individual racer has their own hat that you can unlock. These are the unique hats.
To unlock a hat, you need to either beat a time trial time or win a single race on the specified track. Racing in grand prix mode will not unlock the hats.
The track needed is detailed when highlighting the hat you want to unlock in the selection menu.