A difficult question, and nobody knows the answer for sure. There are lots of theories out there. The two I find most plausible is (1) its a consequence of your brain healing itself when you aren’t using it as much and (2) it is a consequence of your brain assimilating all the data gathered during the day, and putting it in the context of your past experiences.
Ultimately, however, nobody really knows. Animals dream too though!