@Yaoyu **********
You can buy it either. But you need to understand what a re-entry permit is.
A re-entry permit keeps your existing permission of stay stamp alive if you leave Thailand. If you buy it before your extension, then it's only valid for the stamp you have at the time you bought it. If you buy it after your extension, then it's valid for that extension. All it does is make your existing stamp not be cancelled. It doesn't do anything special, there's no trick with it. It's very simple.