In A Midsummer Night’s Dream and Hamlet, the play within the play serves to enhance aspects of the play’s theme and provide comic relief.
In A Midsummer Night’s Dream, the play of “Pyramus and Thisbe” reinforces the theme of the consequences of rash actions and the dangers inherent in love.
Marry, our play is, The Most Lamentable Comedy
and Most Cruel Death of Pyramus and Thisbe. (Act 1, Scene 2)
It also provides comic relief, as the actors flub and overact their way through the performance and the audience lets off steam after the difficult night of chasing, fighting, and misunderstanding. In the play within the play, the two lovers are kept separate, and then Pyramus kills himself when he thinks a lion killed his love, Thisbe. She then kills herself when she finds him dead. The tragedy resulting from misunderstanding demonstrates what almost happened to the lovers in the woods, when they came to blows fighting over Helena after Puck anointed them.
In Hamlet, things are much more serious. Hamlet arranges for everyone to view The Mousetrap, in order to get a reading on King Claudius, saying “The play's the thing/Wherein I'll catch the conscience of the King.” (Act 2, Scene 2, p. 62). Hamlet is convinced that his father was killed by the king, his uncle Claudius.
…This play is the image of a murder done in Vienna. Gonzago is the Duke's name; his wife, Baptista. You shall see anon. 'tis a knavish piece of work; but what o' that? Your Majesty, and we that have free souls, it touches us not….(Act 3, Scene 2, p. 77)
Hamlet thinks he can see this from the king’s reaction to the play whether or not he has a guilty conscience. Since the play itself is about murder, and Hamlet has introduced specific words for the players to day, he thinks he can tell from Claudius’s reaction if he is guilty. He even asks Horatio to do so as well. The play underscores Hamlet’s themes about betrayal and murder, but Hamlet’s bawdy banter with Ophelia also provides comic relief.
As you can see, Shakespeare enjoyed putting plays within plays in order to reinforce both plot and theme, and to insert comic relief.