How long do space maintainers need to stay in mouth?

Until tooth erupts. The space maintainer should stay in the mouth until the tooth erupts into position. The purpose of the space maintainer is to hold the space so that the adjacent teeth do not drift into the space from where a primary tooth had to be extracted early before the permanent tooth was ready to erupt.
As long as needed. A space maintainer is just that, it keeps a space for the adult tooth to erupt into. Once the tooth has started to erupt into the space you don't need the space maintainer anymore.