Hamlet's "to be, or not to be" soliloquy is one of the most important insights into the psyche of Hamlet. At that point in the play, Hamlet's mental state is still in question, as readers ponder whether his insanity is real, feigned, or a combination of both. In the preceding scene, Hamlet's apparent madness has been the topic of discussion, with Polonius surmising that it is a result of his unrequited love for Ophelia. His speech, in which he weighs the relative merits of death by suicide and continuing to live in misery occurs as he enters a room in which Ophelia has been instructed to wait, apparently alone, so that Polonius can observe her interactions with Hamlet. His conversation with he, in which he famously advises "Get thee to a nunnery," adds to the impression that he is disturbed, and it convinces Polonius (and as a result the king and Hamlet's mother) that the prince is mad.
William Shakespeare's The Tragedy of Hamlet, Prince of Denmark, is definitely a tragedy. Unlike many plays in which tragedy intervenes in a previously happy situation, Hamlet is a depressed, bitter young man from the play's beginning all the way to its end. His only glint of optimism is in his plan to trick King Claudius into revealing his role in the murder of Hamlet's father, the previous king and husband to Hamlet's mother, Gertrude, who is betrothed now to Claudius. So, even before Hamlet learns from the ghost of his late father the truth of his murder at the hands of Claudius, the dead king's own brother, the young prince is already angry over his mother's marriage to Claudius. Now, aware of Claudius's evil deed, Hamlet is beyond consolable, a broken man. And, he is being spied upon by everyone around him, including those to whom he is, or should be, closest: Rosencrantz, Guildenstern and Ophelia. Additionally, Polonius and his son, Laertes, who is Ophelia's brother, are determined to eliminate the young prince from the scene.
This, then, is the context in which, in Act III, Scene I, Hamlet delivers perhaps the most famous soliquoy in the history of theater. It is powerful stuff. This young royal should be on top of the world, given his position in life. Instead, he is deeply morose and, as with many teenagers and young adults depressed about their lives, he contemplates suicide. Even in death, however, he cannot escape the pain; dreams will intervene and those dreams may be as bitter as the realities in which he exists. For Hamlet, there may be no escape from the emotional pain he endures. In these thoughts, Hamlet considers death because he cannot envision a positive outcome to the events that have befallen him.