Add an after_spawn hook

I also refactored the hook code to prevent duplication