The venerable shaykh Abdul Fattah Abu Ghuddah (Allah have mercy on his soul) mentions in his Decorum in Islam (Min Adab al-Islam) that at times of death and loss it is beneficial to recall the words of Allah Most High:
“Surely We will try you with something of fear and hunger, and diminution of goods and lives and fruits; yet give thou good tidings unto the patient who, when they are visited by an affliction, say, 'Surely we belong to God, and to Him we return'; upon those rest blessings and mercy from their Lord, and those -- they are the truly guided.” (2:155-157)
He then mentioned some beneficial words that may be mentioned to the bereaved, among them:
A’zam Allahu ajrak wa ahsana 'azaak wa ghafara limayitik
"May Allah magnify your wage, bring about goodness from your grief, and forgive your deceased."
This latter supplication was mentioned by the venerable imam Al-Nawawi (Allah have mercy on his soul) in his Book of Remembrance (Kitab al-Adhkar) where the Imam also mentioned how to condole a non-Muslim which is the same thing that is said to a Muslim less the last phrase "and forgive your deceased":
أعْظَمَ اللهُ أجْرَكَ، وَأَحْسَنَ عَزَاءَكَ
A’zam Allahu ajrak wa ahsana 'azaak
"May Allah magnify your wage and bring about goodness from your grief."
The Imam also noted in the same text that there is no rigidity concerning what may be said to those in grief and that whatever is appropriate and will bring comfort and benefit is admissible. He also identifies the first supplication in the list above as the best thing that may be said due to its firm ascription to the Messenger of Allah (Allah bless him and grant him peace) and the excellence of the hadith it is taken from.
Finally, shaykh Abdul Fattah in the mentioned work on decorum also suggested what one may say oneself when confronted with a loss or affliction:
Allahumma ujurni fi musibati, wakhluf li khairan minha
"O Allah! Compensate me in my affliction, recompense my loss and give me something better in exchange for it…" (Muslim)
In these luminous words, the meanings of which should affect us more than the words themselves, we are reminded of our ultimate purpose in this world and we are, even if by way of grief, afforded an opportunity to flee to the comforting majesty and intimacy of our exalted Lord that perhaps goodness may come from our grief.
May Allah accept from us, realize us in what He teaches us, grant us well-being, and bring about great good from all our states.