Psychologists have struggled to explain why humans, and perhaps other mammals dream for as long as there has been psychology as a supposed science (but I doubt it is). Before that, dreams were thought to have some connection to the spiritual domain, and maybe they still do. Then there was Freud, who saw sex in everything.
But now, a study published in American Academy of Sleep Medicine, puts the case that dreams are a memory processing event, often linked with anticipation of future events, and how the person might cope with them. In short, dreams are a type of testing ground of the mind. That makes more sense than the unsubstantiated ruminations of Freud.