Replacing frame on mountainbike
You may be able to find the same frame new from the manufacturer if your bike wasn't too old. Most bike manufacturers sell bare frames, so even if your frame is no longer available, It might be likely you could find a suitable frame new that all or most of your components fit. Without much info on the frame it is hard to get closer to an answer for you, but compatibility checkpoints would be: the head tube/headset style, seat tube diameter, rear dropout and fork end spacing and axle compatibility, bottom bracket shell size, depending on what kind of suspension your frame has, the rear shock pivot type. You may also have to contend with cable mounting issues depending on how different your new frame is. Did I leave anything out?  Those will be the most significant things to look for.
Used frames are a great option, but as you are saying, There is a potential risk that you end up with a frame that is near or beyond tthe end of it's life. It can be difficult to know looking at a carbon frame what kind of damage if any, and warping or fatigue can be hard to spot on steel and Aluminum frames until you've already spent you money and built up you bike and gone riding. I've purchased a few used frames and had good experiences though. I would try to find a new replacement first for sure, and be open to having to also buy a few new components if not all of your old gear is compatible.