For most applications, most of the time, in the global north, if you're trying to save money then just buying a new wheel is the most economical. The main exception that comes up is if you have a premium quality hub that's built to go indefinitely and is worth re-rimming.
But, good handbuilt wheels offer the highest level of reliability and longevity, and that can have its own economy depending on your situation. In practice a major example of this is that they don't break spokes from fatigue over the course of the service life of the wheel (and really ever with properly stress relieved spokes, but that's a bigger topic) whereas the cheaper end of machine built wheels often will, pushing back against the cost savings of buying one for a bike that gets ridden. And there are also times and places where a rim with life left isn't something you'd throw away. So there is no one answer here. A person who really needs their bike to work as best as possible and also needs to spend the minimum amount of money possible might be perfectly well advised to rebuild the rim.
Another factor is that the world has an overabundance of functional cheap or free used hubs with life left from wheels where the rim died. If you can get a suitable one of those and if minimizing cost is literally the only goal and if you've definitely got a rim with life left, then you're only out the cost of spokes and rebuilding it might make all kinds of sense.
Most rim brake rims are going to be pretty haggard by the time a hub has actually worn out. (Note that 'worn out' implies a different situation than a hub that had issues or failed.) There are exceptions here too; I've rebuilt one or two Dura Ace C50 tubular rims whose hubs died by pressure washer. That's obviously kind of an extreme example, but it happened.
Disc rims that aren't being mountain biked on can have pretty easy lives, especially when paired with a fat tire that's minimizing the severity of the fatigue cycles it experiences.
When rebuilding a used rim or contemplating it, it's a good idea to check for any out of round or out of true spots that are intrinsic to the rim itself, i.e. acquired via damage. A very good way to do this is take the bare rim and lay it on top of a new, high-quality, preferably machined sidewall rim of the same size. Any radial or lateral deformation should be apparent. To be able to get a true wheel with even spoke tension, you want the bare rim to have zero perceptible radial deformation, either flat spots or ovalisation, and 1-2 mm of lateral imperfection at most. (There are methods and tools for getting rims with any of these issues back into shape or at least making them better, but that's another topic.)
When unlacing a rim you intend to rebuild, be gradual so you avoid bending the material around too much. I do half turn loosening passes until the spokes are slack, then I do the rest all at once or cut if they're not being re-used (which they usually shouldn't be).