There is a slight difference between a PhD student and a post-doc, since the former still falls under student rules. For a PhD student I see no problem if you know them outside class, for example from a society or a sports club. If you became familiar with them during teaching, I would suggest you asked for their permission to add them (not just sending an invitation) after the class is over and there is no insinuation of preferential treatment or conflict of interest. If they do not teach you, no problem.
For academics, both early- and late-stage, I would suggest you only followed them on Twitter and only if the account relates on research and academic issues. If you decide to do otherwise, you should definitely ask for permission - just send them a personal message on the platform or ask them in person, the same way you would ask for a business card. Even if they have no issue with it, it is still good manners and professional conduct.
Ultimately it is to the discretion of the other side to accept as @GrayLiterature pointed out. There are good reasons not to, both practical and personal. After graduation, of course, you can do as you see fit.