When yahiko got hurt. Nagato's rinnegan activated and he lost control of himself. Well when yahiko died nagato finally lost it,and his other personality/self awoke and toke control. He decided to continue yahiko's goal to make everyone feel their pain.

konan was so horrified by his power that she was convinced that he was a god.

Somehow with pain's godly ability he was able to sort of bring bodies back to life. So the first person he brought back was yahiko.