It only happens when the battery is aging and the iPhone would otherwise shutdown since it can not handle the voltage peaks. Since the reports Apple has now a battery health section in settings which warns actively when you need to replace the battery. For example my father just replaced the battery in my old 2015 6S plus and it works on full speed again.