When. At the moment bad news lands — a death, a loss, an accident. It is said immediately, before the situation is understood, which is exactly when a person has no words of their own.
The words. The first half is Qur'an, al-Baqara 2:156. Inna lillahi is not "we belong to Allah" in the sense of belonging to a group. The preposition li is possession: we are His. And raji'un is an active participle — not "we will return" but "we are returning", a state currently in progress. Both halves are statements of fact, said at a moment when facts are the last thing anyone wants.
Then the request. Ajurni fi musibati — from ajr, wage: reward me in my affliction, not for it. The affliction is treated as the place the reward is found. And akhlif li khayran minha, from khalaf, succession — replace it with what comes after and is better.
What "better" means. The request is not for the same thing back. A person saying this over an irreplaceable loss is not asking for a duplicate; the word left the replacement unspecified, and the tradition has always read it that way.
How soon. It belongs to the first moment, and its value is understood to lie in being said then, while composure is at its lowest.
On the first half alone. Many say only inna lillahi wa inna ilayhi raji'un on hearing any bad news, large or small. The supplication continues past it, and the second half is the part more often forgotten.