This part and the one below seems to repeat itself in the different hooks, please move them into utility functions for better readability.