Srimad Bhagavatha, in its 11th chapter (Ekadasha skanda) depicts Lord Krishna’s last days. From 6th to 29th chapters there is a narration of Uddhava Gita which is taught by Lord Krishna himself to Uddhava.
During the end of Krishnaavatara, Yadavas had become very arrogant and egoistic. Once sage Agastya along with his followers came to Dwaraka to visit Krishna. Yadavas driven by arrogance and ignorance, planned to humiliate the sages. So they said Saamba (Krishna’s son) to pretend as a pregnant woman and came to the Sages to seek their blessings and requested them to predict the sex of the child. The enlightened sages visualized the reality and cursed the Yadavas that this person would deliver an iron bolt which would destroy the entire Yadava dynasty and went away.
Frightened by the curse they went to king Akrura and Lord Krishna, who in turn told them to cut the iron bolt into tiny pieces and throw it in the ocean. Then Krishna advised Yadavas to go to Prabhas (in Gujarat) and spend rest of their short lives with Bhajans and Satsang. So they all left for Prabhas. While walking on the grass grown on beach, they started fighting among themselves. They hit each other with the grass which they plucked from its root. It so happened that the iron filings thrown into the sea by Yadavas had drifted to the shore at Prabhas and had got stuck to the roots of the grass. Obviously once Yadavas hit each other with grass, the iron filings got stuck to their bodies and all of them died on the spot.
Lord Krishna in Dwaraka came to know about the death of Yadavas and realized that his time also came to an end. So when he got prepared to leave, Uddhava, Krishna’s childhood friend and also his charioteer at times was deeply in sorrow. Looking at his best friend in grief, Krishna started preaching Vedanta to him. This was called Uddhava Gita. Krishna mentioned that he had taught this earlier in his previous avataras. Immediately Uddhava asked about Krishna’s previous avataras and to whom he had taught. Krishna replied that "once Brahma’s children- Sanat kumaras, who were born first, went to their father and asked about a doubt which they had in Philosophy. They were believed to be born Sanyasis. Unfortunately even Brahma did not know the answer, so he meditated upon Lord Vishnu and after some time, Vishnu appeared in the form of a Hamsa or white Swan and asked Brahma and Sanat Kumaras about their problem. Then Sanat Kumaras said that we know mind is made of three gunas – satvika, Rajasika and Tamasika, and the world is also made up of same three gunas, how dowe separate mind from the world. Lord Vishnu was pleased to answer the question". Since Vishnu was in the form of Hamsa, the teachings is also called Hamsa Gita.