How can a Muslim remain optimistic in time of trials and afflictions? How can we learn not to despair?

Question

Trials and tribulations are part of human life. Allah Ta’ala reminds us: And We will surely test you with something of fear and hunger and a loss of wealth and lives and fruits, but give good tidings to the patient. (2:155) There are four possible reasons for trials or afflictions: (1) they are to test the faith (Imaan) of a person. (2) They happen to train or educate a true believer in patience and dependence on Allah Ta’ala and to face the difficult realities of life in this world. (3) They could befall to elevate the status of a true believer. (4) And they could be a result of one’s own sins and mistakes and compensation for one’s wrong doings.