It's probably not for money, at upper-division or graduate level, because one will not make much. Better to work part-time at a fast-food place or coffee shop. Also, not much "prestige" of any sort. And, no, does not count toward getting tenure (and may count against, subliminally).
The real reason (I think, certainly in my own direct experience) is that one simply can't help oneself. This ought not be entirely surprising, since, after all, most people who go into academic mathematics do not do so because the contemporary commodified form of universities and mathematics exactly suits them, but because they like engagement with mathematics, perhaps to the degree that they can mostly overlook the artificial rules.
So, yes, after teaching various versions of a course several times, one may easily discover that many of the traditional textbooks have at least one failing, namely, that they attempt to include too much, to avoid alienating anyone who'd be alienated by omission of their pet topic. Or, oppositely, stay too elementary, to avoid alienating another demographic.
So, yes, one might choose to compose course notes for the courses one teaches, to match one's notion of what those courses should be. No, it is not for external reward, but almost entirely so that one does not have to "battle" with the "recommended text(s)". (Especially before it was possible to easily typeset mathematics, I experienced many episodes of students being unwilling to believe the palpable mathematical truth of what I was telling them, because the recommended text either omitted the topic or had "different definitions". It was annoying.)
Another point is to make a coherent account freely available... which is somewhat orthogonal to creation of traditional textbooks, which are still mostly not freely available. However, some publishers (e.g., Cambridge Univ Press) are happy to negotiate details.
And, last, although writing "books" has very little cachet for most purposes, having notes approved by a conventional publisher is slightly higher-status than having no vetting at all. It shows external approval, etc.
EDIT: also, although "by the rules", a textbook is not "original scholarly work", in fact, it easily can be. That is, in addition to the non-trivial questions of what to include, what to omit, and how to treat the things, there is a subtler (possibly not-so-quantifiable... for the current impact-factor sort of ... noise) manifestation of expert-tone, expert-appraisal, and such. So, yes, it is possible to write textbooks that are not at all scholarly, beyond a modestly competent collecting of well-known standard things. At the same time, it is possible to do better, and, to do better requires considerable expertise and judgement, apart from the logistics, and should be (and mostly is, but off-the-record) respected.