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.