Grimlock doesn't actually try to fight Optimus Prime before helping him. He's initially hostile and suspicious towards the Autobots, believing they're trying to steal his precious "treasure" (a Cybertronian artifact).
Here's why he initially acts this way:
* Paranoia: Grimlock, as a Dinobot, is a powerful and independent warrior. He's been through a lot and seen many civilizations rise and fall. He's naturally suspicious of others, especially those with a similar technological level.
* Misunderstanding: Grimlock doesn't understand the situation fully. He doesn't realize the Autobots are allies. He sees them as another threat, and acts accordingly.
* Protecting his treasure: Grimlock's treasure is significant to him, and he doesn't want anyone taking it. He believes the Autobots want to steal it, and he's prepared to fight to protect it.
Once Optimus Prime shows Grimlock that the Autobots aren't a threat and are actually working to protect humanity, Grimlock joins forces with them.
It's worth noting that the film doesn't necessarily explain Grimlock's exact motivations in detail. This leaves some room for interpretation, but ultimately, his initial hostility is based on his distrust of the Autobots and his fierce desire to protect his precious treasure.