This is likely one of the most hotly debated questions about the play and one that brings out all kinds of different answers. There is significant evidence to suggest that he is, at least some of the time, pretending to be crazy. At the beginning of the play it is difficult to tell as he is seeing ghosts and many of the people around him are worried for him because of the death of his father and his continuous mourning and melancholy.
As time goes on, however, it becomes clear that he is lucid at least some of the time as he plans to have Claudius think that he is crazy in order to throw off some suspicion and give Hamlet time to arrange his plans. He tells his mother to say as much to Claudius and he mocks Polonius rather pointedly in a way that suggests his madness is at least madness with a clear object and not the madness that drives Ophelia to kill herself.
In corroborating the good answer above, I would say that Hamlet is not really crazy. He himself declares at the beginning of the play to his friend Horatio, after he has met with his ghost father. He confided in his friend that he would right away put on a strange attitude,which is,that show of madness. He uses it as a guise to prevent suspicion of his mission to avenge his father's death. He's not really crazy though not in the real sense of it. He just feigns madness. This 'antic disposition' is also used as a cover-up for his depressed and sorrowful mind.