you can transit via hongkong no matter you are back or leave mainland of China. but if you are already in the mainland, you'd better to apply a tran-permit. that is really important. if not, you will have big problem in the airport or other custom points.
i have tried this autumn. so definitely no problem by following my method.